查询 Django 模型以包含和排除项目

Querying django models to include and exclude items

我目前有 2 个这样的模型

class Recipe(models.Model):
    account = models.ForeignKey(CustomUser, on_delete=models.CASCADE, null=True, blank=True)
    name = models.TextField(null=True, blank=True)
    slug = models.SlugField(null=False, blank=True, unique=True)
    image_path = models.ImageField(upload_to=MEDIA_URL, null=True, blank=True)
    description = models.TextField(null=True, blank=True)
    date_added = models.DateField(auto_now_add=True)

class RecipeIngredients(models.Model):
    recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE, null=True)
    ingredient = models.TextField(null=True, blank=True)
    quantity = models.CharField(max_length=10, null=True, blank=True)
    type = models.CharField(max_length=50, null=True, blank=True)

我正在尝试进行查询,如果我有一个包含 2 个或更多项目的列表,比如

ingredients = ["egg", "bacon", "rice"]

对我来说 returns 只有完全包含鸡蛋、培根和米饭或更少的食谱。

我能够以一种 hacky 的方式做到这一点,但它真的很慢而且我觉得没有正确使用 ORM。

ingredients = ["egg", "bacon", "rice"]
results = []
recipes = []
for i in ingredients:
    r = RecipeIngredients.objects.filter(ingredient__icontains=i)
    results.append(r)
for result in results:
    for r in result:
        recipes.append(r.recipe)
for r in recipes:
    recipeingredients = r.recipeingredients_set.all()
    for ri in recipeingredients:
        ingredient = ri.ingredient
        if ingredient not in ingredients:
            try:
                recipes.remove(r)
            except:
                print(r)
    print("end of recipe")

任何关于如何使这个查询更正确的帮助将不胜感激。

你可以使用原始 sql,像这样:

recipe_list = Recipe.objects.raw('select a.*
   from app_Recipe a 
   inner join app_RecipeIngredients b
      on a.id = b.recipe_id and b.ingredient in ("egg", "bacon", "rice")
   group by a.*
   having count(*) >= 2')

可以将 app_ 替换为您的项目名称,将 a.* 替换为列名列表。