or?

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)


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))

You can use the | operator to combine querysets directly without needing Q objects:

result = Item.objects.filter(item.creator = owner) | Item.objects.filter(item.moderated = False)

(edit - I was initially unsure if this caused an extra query but @spookylukey pointed out that lazy queryset evaluation takes care of that)


You want to make filter dynamic then you have to use Lambda like

from django.db.models import Q

brands = ['ABC','DEF' , 'GHI']

queryset = Product.objects.filter(reduce(lambda x, y: x | y, [Q(brand=item) for item in brands]))

reduce(lambda x, y: x | y, [Q(brand=item) for item in brands]) is equivalent to

Q(brand=brands[0]) | Q(brand=brands[1]) | Q(brand=brands[2]) | .....
链接地址: http://www.djcxy.com/p/6580.html

上一篇: Django过滤器与获取单个对象?

下一篇: 要么?