Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django filter on queryset intersection?

class Item(models.Model):
    ...

class ItemSet(models.Model):
    items = models.ManyToManyField(Item, related_name="itemsets")

I have a list of ItemSets. I want to find all Item objects where the Item object is in the "items" M2M field on at least one of the ItemSet objects.

How can I do this?

P.S. Here is what I have tried, but to no avail:

itemset_list = [itemset1, itemset2, itemset3]    
items = Item.objects.filter(itemsets__in=itemset_list)
like image 706
Andrew Avatar asked May 06 '12 18:05

Andrew


1 Answers

If you need your list of itemsets and you didn't get them from a query, try this:

itemset_list = [itemset1, itemset2, itemset3]
itemset_list_ids = [itemset.id for itemset in itemset_list]
itemset_queryset = ItemSet.objects.filter(id__in=itemset_list_ids)
items = Item.objects.filter(itemsets__in=itemset_queryset)

If you can get your itemset list by querying, that shortens it a little bit:

itemset_queryset = ItemSet.objects.filter(SOME FILTER HERE)
items = Item.objects.filter(itemsets__in=itemset_queryset)
like image 193
Paragon Avatar answered Nov 06 '22 03:11

Paragon