QuerySet for non-empty TextField
For a model like:
class Item(models.Model):
notes = models.TextField(blank=True)
....
I'm attempting to do a simple queryset for all Items where the "notes" field is non-empty. Not finding mention of this capability in the docs, but via a comment on a bug report, discovered that you can actually compare with greater than:
items_with_notes = Item.objects.filter(notes__gt='')
This works, but feels like a hack. "Greater than" seems like it should be开发者_高级运维 used for numeric comparisons, not for checking whether a text field is blank. Surprised not to find something like:
Item.objects.exclude(notes=blank)
Am I overlooking something, or is .filter(notes__gt='') the right way to do it?
.exclude(notes=u'')
Read more here: django.db.models.query.QuerySet.exclude
you can also use Q object:
from django.db.models import Q
Item.objects.filter(~Q(notes=''))
精彩评论