我目前正在try 使用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的理解,这将退还所有只包含"鸡蛋"、"培根"和"土豆"的物品,但不包括鸡蛋或炒蛋.是否需要调整此选项,使其搜索所有包含成分的项目,并且不含case?

推荐答案

可以创建条件的析取,包括:

from django.db.models import Q

ingredients = ['eggs', 'bacon', 'potato']

recipes = Recipe.objects.filter(
    Q(
        *[('recipeingredients__ingredient__icontains', ingredient) for ingredient in ingredients],
        _connector=Q.OR
    )
).alias(
    ningredient=Count('recipeingredients')
).filter(
    ningredient__gte=len(ingredients)
)

一个潜在的问题可能是,如果查询是eggs,并且两个成分匹配,例如'white eggs''brown eggs',那么这两个成分将计为two,因此另一个成分,例如bacon可能不是成分,并且仍然是QuerySet的一部分,因此不幸的是,要生成一个完全匹配所有成分的QuerySet并不容易.

潜在的解决方案可能是:

ingredients = ['eggs', 'bacon', 'potato']

recipes = Recipe.objects.all()

for ingredient in ingredients:
    recipes = recipes.filter(recipeingredients__ingredient__icontains=ingredient)

但这将使n个成分加入n个,因此对于大量的ingredients个成分很容易变得不可行.

Django相关问答推荐

如何在Django中显示文件大小

Urls.py中路径**kwargs的Django翻译?

Django:添加第二个';详细';用于检索额外信息的视图

如何在Django CMS中更新上下文

ModuleNotFoundError:没有名为guardian.shortcuts的模块

如何计算 Django 模型中特定对象的数量?

Django 应用程序似乎无法识别相关名称?

超级用户在基于类的视图中进行身份验证

如何在 Django 中将下一个 8 月 1 日添加为 DateTimeField 默认值

Django 有脚手架吗?

使用 args 和选项编写自定义管理命令 - 所需字段说明

Django 从 url 保存图像并与 ImageField 连接

如何在 django tests.py 中创建管理员用户

Django - 在模板中显示当前日期和时间

可以在 github 页面上托管 django 站点吗?

在 virtualenv Ubuntu 12.10 中使用 pip 安装 lxml 错误:command 'gcc' failed with exit status 4

有 Django List View 模型排序吗?

如何使用基于类的视图处理表单(通过 get 或 post)?

Django manage.py:在其依赖之前应用迁移

如何更改 ModelForm 中所有 Django 日期字段的默认小部件?