Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 928
shacker Avatar asked Jan 31 '10 09:01

shacker


People also ask

What is Queryset?

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.

How check field is null in Django?

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.

How do I check if a query set is null?

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.


2 Answers

.exclude(notes=u'')

Read more here: django.db.models.query.QuerySet.exclude

like image 170
Ignacio Vazquez-Abrams Avatar answered Sep 28 '22 08:09

Ignacio Vazquez-Abrams


you can also use Q object:

from django.db.models import Q
Item.objects.filter(~Q(notes=''))
like image 43
Sergey Avatar answered Sep 28 '22 06:09

Sergey