筛选中介ManyToMany django [英] Filter intermediary ManyToMany django
问题描述
class Ingredient(Model):
name = CharField(max_length=55, unique=True)
def __str__(self):
return self.name
class Meta:
ordering = ('name',)
class Product(Model):
name = CharField(max_length=55)
def __str__(self):
return self.name
class Meta:
ordering = ('name', )
class ProductIngredient(Model):
product = ForeignKey(Product, on_delete=CASCADE, related_name='product_ingredients')
ingredient = ForeignKey(Ingredient, on_delete=CASCADE)
optional = BooleanField(default=False)
class Meta:
unique_together = (('product', 'ingredient'),)
ordering = ('product__name',)
def __str__(self):
return f'{self.product} - {self.ingredient}'
我要进行两个查询:
- sele ct所有成分包含草莓和牛奶的产品
- 选择所有成分包含草莓或牛奶的产品
第一个查询是: Product.objects.prefetch_related('product_ingredients__ingredient')。filter(product__ingredients__ingredient__name ='strawberry')。filter(product__ingredients__ingredient__name ='milk')
我需要在第一个查询中写 distinct
吗?
如何编写第二个查询?
Do I need to write distinct
in the first query?
How to write the second query?
推荐答案
Do I need to write distinct in the first query?
否,或者如果 product
-成分
的组合是唯一的,例如此处。这将是截然不同的,因为两种成分是截然不同的。此外,除非您确实要使用相关的呈现 Product
,否则您不应在此处使用 .prefetch_related(..)
成分
s。这样就足够了:
No, or at least not if the product
-ingredient
combination is unique, like here. It will be distinct, since the two ingredients are clearly distinct. You furthermore should not use .prefetch_related(..)
here, unless you really want to render the Product
with the related Ingredient
s. So it is sufficient to write:
Product.objects.filter(
product__ingredients__ingredient__name='strawberry'
).filter(
product__ingredients__ingredient__name='milk'
)
如何编写第二个查询?
How to write the second query?
您可以使用> __ in
查找[Django-doc] :
Product.objects.filter(
product__ingredients__ingredient__name__in=['strawberry', 'milk']
)
这篇关于筛选中介ManyToMany django的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!