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)
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With