Проблема необработанного sql-запроса в Django
Я пытаюсь составить SQL-запрос для реализации ответа, данного здесь.
Пользователь предложил мне попробовать выполнить необработанный 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)
Любая помощь будет оценена по достоинству
Вы можете сделать запрос с помощью:
from django.db.models import Count
ingredients = ["eggs", "bacon", "rice"]
Recipe.objects.filter(
recipeingredients__ingredient__in=ingredients
).alias(
ningredient=Count('recipeingredients')
).filter(
ningredient__gte=len(ingredients)
)