我正在尝试使用SQL查询来实现给定的答案
here
。
用户建议我尝试执行原始sql查询来解决。我在落实他的建议时遇到了一些问题。
例如,这就是我目前所拥有的。
ingredients = ["eggs", "bacon", "salt"]
recipes = Recipe.objects.raw('select whattocook_RecipeIngredients \
from whattocook_Recipe a \
inner join whattocook_RecipeIngredients b \
on a.id = b.recipe_id and b.ingredient in (ingedients) \
group by recipeingredients \
having count(*) >= 2')
但这不起作用。他的回答是这样的
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')
maybe replace app_ with your project name, replace a.* with list of column names.
所以我认为我误解了我需要替换哪些列,因为我的代码给了我这个错误。
django.db.utils.ProgrammingError: column "ingedients" does not exist
LINE 1: ... on a.id = b.recipe_id and b.ingredient in (ingedients...
^
HINT: Perhaps you meant to reference the column "b.ingredient".
我的应用程序名为whattocook,模型如下
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)
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)
preptime = models.IntegerField(null=True, blank=True)
cookingtime = models.IntegerField(null=True, blank=True)
cookingtimeoptions = models.CharField(max_length=100, null=True, blank=True)
preptimeoptions = models.CharField(max_length=100, null=True, blank=True)
servings = models.CharField(max_length=100, null=True, blank=True)
rating_value = models.IntegerField(null=True, blank=True)
rating_count = models.IntegerField(null=True, blank=True)
categories = models.ManyToManyField('Category', blank=True)
date_added = models.DateField(auto_now_add=True)
任何帮助都将不胜感激