views:

41

answers:

1

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?

+5  A: 

.exclude(notes=u'')

Ignacio Vazquez-Abrams
Ah, much better, thanks. I notice this works either with or without the "u" before the quotes. So what does the "u" accomplish?
shacker
The `u` in front of the string makes it a `unicode` literal. It doesn't accomplish much here, since the empty `str` decodes to the empty `unicode` trivially. It does save a tiny bit of time, but not enough to really worry about. I use unicode literals there always because Django uses unicode internally, and if something non-ASCII comes up then you don't want Django choking on it because you scrimped on a single keystroke.
Ignacio Vazquez-Abrams
Got it, thanks much.
shacker