使用字段的字符串表示查询 BooleanFields

Query on BooleanFields using string representations of the fields

如何在给定属性的字符串表示形式的情况下过滤模型的布尔字段,该属性表示为真?

举个例子,给定:

class MealBooking(models.Model):

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


meal = "breakfast"

我如何过滤所有包含 True 的 MealBookings,用于由 meal 表示的字段?

您可以过滤:

MealBooking.objects.filter(<b>**{meal: True}</b>)

因此我们首先创建一个字典。例如,如果 meal'breakfast',字典将看起来像 { <b>'breakfast'</b>: True }

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

调用 .filter(…)