简体   繁体   中英

Filtering a Django model using the related names of 2 M2M fields

I have the following structure in my models:

class Sauce(models.Model):
    ...

class Topping(models.Model):
    ...

class Pizza(models.Model):
    sauces = models.ManyToManyField(Sauce, related_name='pizzas')
    toppings = models.ManyToManyField(Topping, related_name='pizzas')

Now, lets say I want to query all the pizzas given a list of toppings and sauces. For example:

sauces_ids = [2, 5, 7, 8]
toppings_ids = [1, 4, 5, 21]

What is the most efficient way to query this using Django's ORM? Thanks for any help.

Pizza.objects.filter(sauces__source_id__in=[2,5,6,8], toppings__topping_id__in=[1, 4, 5, 21])

Assuming those are values of pk / id field, you can use the __in lookup:

Pizza.objects.filter(sauces__in=sauces_ids, toppings__in=toppings_ids)

If those are values of some other field, you need to reference the field name as well, eg with field name field :

Pizza.objects.filter(sauces__field__in=sauces_ids, toppings__field__in=toppings_ids)

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