2

鉴于这段代码(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'
4

1 回答 1

1

您可以使用以下方式过滤:

Recipe.objects.filter(
    ingredients__name='tomato'
).filter(
    ingredients__name='onion'
)

通过使用两个.filter(…)[Django-doc]调用,我们创建了两个 LEFT OUTER JOINs,一个用于搜索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

另一种选择是制作一个 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))

或在之前:

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)
于 2021-07-29T21:51:59.423 回答