views:

559

answers:

2

How would I do an "or" in a django filter.

Basically, I want to be able to list the items that either a user has added (they are listed as the creator) or the item has been approved

so I basically need to select

item.creator = owner or item.moderated = False

How would I do this in django (preferably with a filter/queryset)

+11  A: 

There is Q objects that allow to complex lookups. Example:

from django.db.models import Q

Item.objects.filter(Q(creator=owner) | Q(moderated=False))
Alex Koshelev
+2  A: 

There is a simpler way but I'm not sure if it hits the database twice.

Use the | operator:

result = Item.objects.filter(item.creator = owner) | Item.objects.filter(item.moderated = False)
andybak
To find out which queries are executed on a given request, you can use the debug-toolbar Django application. It's made of awesome and win.
Deniz Dogan
I was testing this from the shell. Is there a way to trace the queries for the above line directly from the shell?
andybak