微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

我正在使用 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'
)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。