鉴于这段代码(Python & TortoiseORM):
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)
如何查询包含 BOTH Ingredient.name="tomato" 和 Ingredient.name="onion" 的所有食谱?我相信在 Django-ORM 中,可以使用 & 运算符或 intersect 方法创建一些查询集的交集。
更新#1
这个查询有效,但在我看来有点混乱,当我想查询所有包含超过 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'