如何解决如何从他的多对多关系中选择包含某些孩子的父母?
class Recipe(Model):
description = fields.CharField(max_length=1024)
ingredients = fields.ManyToManyField(model_name="models.Ingredient",on_delete=fields.SET_NULL)
class Ingredient(Model):
name = fields.CharField(max_length=128)
如何查询包含 Ingredient.name="tomato" 和 Ingredient.name="onion" 的所有食谱? 我相信在 Django-ORM 中,可以使用 & 运算符或 intersect 方法创建一些 QuerySet 的交集。
更新 #1
这个查询有效,但在我看来它有点混乱,当我想要 f.e. 时它会出现问题。查询包含超过 2 种成分的所有食谱。
subquery = Subquery(Recipe.filter(ingredients__name="onion").values("id"))
await Recipe.filter(pk__in=subquery,ingredients__name="tomato")
更新 #2
SELECT "recipe"."description","recipe"."id"
FROM "recipe"
LEFT OUTER JOIN "recipe_ingredient"
ON "recipe"."id" = "recipe_ingredient"."recipe_id"
LEFT OUTER JOIN "ingredient"
ON "recipe_ingredient"."ingredient_id" = "ingredient"."id"
WHERE "ingredient"."name" = 'tomato'
AND "ingredient"."name" = 'onion'
解决方法
您可以过滤:
Recipe.objects.filter(
ingredients__name='tomato'
).filter(
ingredients__name='onion'
)
通过使用两个 .filter(…)
[Django-doc] 调用,我们创建了两个 LEFT OUTER JOIN
,一个用于搜索 tomato
,另一个用于搜索 onion
。这显然只适用于 Django ORM,不适用于 Tortoise ORM。
如果我们使用 print(qs.query)
(构造查询),我们得到:
SELECT recipe.id,recipe.description
FROM recipe
INNER JOIN recipe_ingredients ON recipe.id = recipe_ingredients.recipe_id
INNER JOIN ingredient ON recipe_ingredients.ingredient_id = ingredient.id
INNER JOIN recipe_ingredients T4 ON recipe.id = T4.recipe_id
INNER JOIN ingredient T5 ON T4.ingredient_id = T5.id
WHERE ingredient.name = tomato
AND T5.name = onion
另一种选择是制作一个single LEFT OUTER JOIN
,并检查项目数是否与项目数匹配,因此:
from django.db.models import Count
items = {'tomato','onion'}
Recipe.objects.filter(
ingredients__name__in=items
).alias(
ncount=Count('ingredients')
).filter(ncount=len(items))
或django-3.2之前:
from django.db.models import Count
items = {'tomato','onion'}
Recipe.objects.filter(
ingredients__name__in=items
).annotate(
ncount=Count('ingredients')
).filter(ncount=len(items))
因此,这提供了如下所示的查询:
SELECT recipe.id,recipe.description
FROM recipe
INNER JOIN recipe_ingredients ON recipe.id = recipe_ingredients.recipe_id
INNER JOIN ingredient ON recipe_ingredients.ingredient_id = ingredient.id
WHERE ingredient.name IN (onion,tomato)
GROUP BY recipe.id
HAVING COUNT(recipe_ingredients.ingredient_id) = 2
特别是 HAVING COUNT(recipe_ingredients.ingredient_id)
是这里的关键,因为 WHERE
子句已经将其过滤为仅洋葱和西红柿。
这要求成分的 name
是唯一的(即没有两个同名的 Ingredient
记录)。您可以使用以下命令使 name
字段唯一:
class Ingredient(Model):
name = fields.CharField(unique=True, max_length=128)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。