python - Querying for Multiple ManyToMany Fields -
i have model, entry
, manytomany
field:
tags = models.manytomanyfield(tag)
the tag
model simple:
class tag(models.model): name = models.charfield(max_length=25) def __unicode__(self): return self.name
i want create function, getentrybytags
takes list of tag names , returns entry has tags. if knew number of tags , names of each, trivial:
entry.objects.filter(tags__name="tech").filter(tags__name="music").filter(tags__name="other")
but since going based on user input , tags number variable, i'm not sure how proceed. how iterate on multiple item list object contains each of manytomany objects names represented in list?
you can try,
from django.db.models.query_utils import q tag_name_list = xxx # dynamic tag name list based on user input query_list = [q(tags__name=tag_name) tag_name in tag_name_list] query_set = entry.objects query in query_list: query_set = query_set.filter(query) return query_set
Comments
Post a Comment