如何检查对象是否在其多对多关系中包含某些对象?

时间:2021-07-27 21:46:48

标签: python database postgresql tortoise-orm

我正在使用 Tortoise-ORM,我认为它基于 Django-ORM。

假设我的数据库如下所示:

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)

是否可以使用单个内置的过滤器方法来查询名称为“番茄”和“洋葱”的所有食谱?

更新 #1

我尝试使用:
Recipe.filter(Q(ingredients__name='tomato') & Q(ingredients__name='onion'))

但它不起作用,并且从该语句生成的原始 sql 无效。

 select "recipe.id", "recipe.description"
 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" = 'potato'
)

0 个答案:

没有答案