首页 > 解决方案 > 使用字段的字符串表示形式查询 BooleanFields

问题描述

我如何过滤模型的布尔字段,给定属性的字符串表示形式,对于该属性意味着 true?

例如,给定:

class MealBooking(models.Model):

    breakfast = models.BooleanField()
    lunch = models.BooleanField()
    dinner = models.BooleanField()


meal = "breakfast"

如何过滤所有 MealBookings 包含True的字段代表的字段meal

标签: djangodjango-modelsdjango-orm

解决方案


您可以使用以下方式过滤:

MealBooking.objects.filter(**{meal: True})

因此,我们首先创建一个字典。meal例如,如果是'breakfast',则字典将如下所示。{ 'breakfast': True }

**然后我们通过在前面添加两个星号 ( ) 将字典解包为命名参数。因此,这意味着如果字典是{ 'breakfast': True },我们调用.filter(…)with .filter(breakfast=True)


推荐阅读