简体   繁体   中英

Query based on ManytoMany Field Django

I have the following models on which I want to query based on ManytoMany Field:

class Topping(models.Model):
    topping_name=models.CharField(max_length=16)

class Cart_Item(models.Model):
    pizza=models.ForeignKey(Pizza, blank=True, null=True, on_delete=models.CASCADE)
    toppings=models.ManyToManyField(Topping, blank=True)
    quantity=models.IntegerField()

I have a list of toppings available with me. I want to query a Cart_Item where toppings field contains all the values in the list. For example if my list is toppings_list=["Pepperoni","Mushroom"] , then I want the Cart_Item where toppings contains only these 2 toppings. How can I query like that?

I think this is an option.


cart_items = (Cart_Item.objects.annotate(num_toppings=Count('toppings'))\
.filter(num_toppings__exact=2))\
.filter(toppings__topping_name=toppings_list[0])\
.filter(toppings__topping_name=toppings_list[1])

If list includes many data, then you can chain querysets in a loop.

for topping in toppings_list:
    cart_items = cart_items.filter(toppings__topping_name=topping)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM