Django ORM __in 但不是精确的,而是包含不区分大小写的?

标签 django django-models django-orm

我目前正在尝试使用 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/

相关文章:

python - 如何在 Django 模型上将月份表示为字段

python - Django 两个内连接

python - 我如何将Django与Parcel结合起来?

django - 当我尝试发布新帖子时,我收到 'django.db.utils.IntegrityError: null value in column "user_id“违反非空约束”

django - 在 AWS 上使用 MongoDB 部署 Django 应用程序

python - 我可以将 Django 的通用 View 与 google-app-engine-django 一起使用吗?

django - 在 Django 自定义管理器类中使用另一个模型管理器的代码

mysql - Django ORM - 具有不同选择子句的分组聚合

django 中的 Python 代码打印当前版权年份

sql - 从 postgres View 中选择时,Django 返回错误结果