On Sun, Feb 8, 2009 at 8:03 AM, J <jobce...@gmail.com> wrote:
>
> The idea is to be able to query all the items that have a specific 'group'
> record chosen, as well as all items that don't have anything set. Since some
> of them can be NULL or None, how do I go about selecting in a query both the
> items that are NULL, as well as the items that are linked to a specific
> 'group' in the related table?
>
> This does not work:
> qs = menuitem.objects.all().filter(group__in=[None, 1])
>
> This works:
> qs = menuitem.objects.all().filter(group=None)
>
> This works:
> qs = menuitem.objects.all().filter(group=1)

The confusion here is the result of a little concept leakage on the
part of the Django ORM.

In SQL, you can't actually ask for a field that is " = NULL", because
by definition, _nothing_ is equal to NULL. Django helps out here by
rolling out "group=None" filters to the SQL "group IS NULL"

When you ask for the query group__in=[None, 1], this will roll out as
"group IN (NULL, 1)", which obviously won't work for the NULL case.

What you need to do is use an OR to combine your the two queries that
work, making a special case of the NULL option:

qs = menuitem.objects.all().filter(group=None) |
menuitem.objects.all().filter(group=1)

If you have multiple non-null groups that you want to compare to, you
can use the __in operator on the second clause:

qs = menuitem.objects.all().filter(group=None) |
menuitem.objects.all().filter(group__in=[1,2])

You just can't include the None in the __in - it needs to be made a
special case.

Yours,
Russ Magee %-)

--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to