Django ManyToMany Queryset AND instead of OR -
i have following query:
things = thing.objects.filter(tags__in=selected_tags).distinct()
if selected_tags looks this:
selected_tags = [<tag: tag1>, <tag: tag2>]
then things contain thing has tag1 or tag2.
i want query gives me things have tag1 , tag2 (and maybe tag3, not necessarily). best way this?
__in
inherently or-based. literally says pull out row has 1 of these tags. create , based query, you'd need filter each tag individually:
thing.objects.filter(tags=tag1, tags=tag2, ...)
that's not ideal, , unfortunately, can't use expanded dictionary in scenario because of key's same. other option use q
:
from django.db.models import q query = none tag in tags: if query none: query = q(tags=tag) else: query &= q(tags=tag) things = thing.objects.filter(query)
it's bit convuluted, if need dynamically create query (instead of hardcoding each tag you're searching for), it's best bet.
Comments
Post a Comment