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?
A QuerySet is a collection of data from a database. A QuerySet is built up as a list of objects. QuerySets makes it easier to get the data you actually need, by allowing you to filter and order the data.
null=True will make the field accept NULL values. Blank values for Django field types such as DateTimeField or ForeignKey will be stored as NULL in the database.
In Django queryset we have __isnull to check if a value is null. Here were filtering all the values from MyModel model, which have an alias = Null. exclude allows you to pass multiple arguments, it will the then check for every argument. If your query is still more complex, you can use Django's Q Objects.
.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=''))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With