On Sat, Feb 7, 2009 at 8:08 PM, J <jobce...@gmail.com> wrote: > Truly amazing. I would have never guessed that the OR operator would > combine two querysets. How does that work? > > Thanks for your help. You solved my problem. > J > > > > > Russell Keith-Magee wrote: > > On Sun, Feb 8, 2009 at 8:03 AM, J <jobce...@gmail.com> <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 %-) > > > > > > > > > > __or__ on an object allows you to define the behavior on a or. http://code.djangoproject.com/browser/django/trunk/django/db/models/query.py#L251is the magic that makes it happen
-- "I disapprove of what you say, but I will defend to the death your right to say it." --Voltaire "The people's good is the highest law."--Cicero --~--~---------~--~----~------------~-------~--~----~ 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 -~----------~----~----~----~------~----~------~--~---