简体   繁体   English

使用2个M2M字段的相关名称过滤Django model

[英]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?使用 Django 的 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:假设这些是pk / id字段的值,您可以使用__in查找:

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 :如果这些是其他字段的值,您还需要引用字段名称,例如使用字段名称field

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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