我目前正在尝试使用 Django ORM 来查询 Recipe
模型的成分。
class Recipe(models.Model):
account = models.ForeignKey(CustomUser, on_delete=models.CASCADE, null=True, blank=True)
name = models.TextField(null=True, blank=True)
class RecipeIngredients(models.Model):
recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE, null=True)
ingredient = models.TextField(null=True, blank=True)
到目前为止我所拥有的是
ingredients = ["eggs", "bacon", "potato"]
recipes = Recipe.objects.filter(
recipeingredients__ingredient__in=ingredients
).alias(
ningredient=Count('recipeingredients')
).filter(
ningredient__gte=len(ingredients)
)
根据我对this answer的理解这将返回仅包含“鸡蛋”、“培根”和“土 bean ”的所有项目,但不包括鸡蛋或炒鸡蛋。是否有办法调整它以使其搜索包含成分且不区分大小写的所有项目?
最佳答案
您可以使用以下方法创建条件析取:
from django.db.models import Q
ingredients = ['eggs', 'bacon', 'potato']
recipes = Recipe.objects.filter(
Q(
*[<strong>('recipeingredients__ingredient__icontains', ingredient) for ingredient in ingredients</strong>],
_connector=Q.OR
)
).alias(
ningredient=Count('recipeingredients')
).filter(
ningredient__gte=len(ingredients)
)
一个潜在的问题可能是,如果查询是鸡蛋
,并且两种成分匹配,例如'白鸡蛋'
和'棕色鸡蛋'
>,这些将算作两个,因此另一种成分(例如培根
)可能不是成分,但仍将是QuerySet
的一部分,因此不幸的是,制作一个完全匹配所有成分的 QuerySet
并不容易。
潜在的解决方案可能是:
ingredients = ['eggs', 'bacon', 'potato']
recipes = Recipe.objects.all()
for ingredient in ingredients:
recipes = recipes.filter(recipeingredients__ingredient__icontains=ingredient)
但这将使 n 个成分进行 n 个 JOIN,因此对于大量成分
很容易变得不可行。
关于Django ORM __in 但不是精确的,而是包含不区分大小写的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72438983/