django - 使用字段的字符串表示形式查询 BooleanFields
问题描述
我如何过滤模型的布尔字段,给定属性的字符串表示形式,对于该属性意味着 true?
例如,给定:
class MealBooking(models.Model):
breakfast = models.BooleanField()
lunch = models.BooleanField()
dinner = models.BooleanField()
meal = "breakfast"
如何过滤所有 MealBookings 包含True
的字段代表的字段meal
?
解决方案
您可以使用以下方式过滤:
MealBooking.objects.filter(**{meal: True})
因此,我们首先创建一个字典。meal
例如,如果是'breakfast'
,则字典将如下所示。{ 'breakfast': True }
**
然后我们通过在前面添加两个星号 ( ) 将字典解包为命名参数。因此,这意味着如果字典是{ 'breakfast': True }
,我们调用.filter(…)
with .filter(breakfast=True)
。
推荐阅读
- javascript - 浏览器忽略我的 JavaScript 版本时间戳?
- arrays - C:创建一个变量依赖于运行时函数的静态数组?
- jquery - 使用 jquery.table2excel.js 将 HTMLtable 导出到 Excel 时出现日期格式问题
- postgresql - (postgres)不同类型的数据对不同的列有自己的限制
- python - 带有嵌套项目符号的 ReportLab 编号
- python - 用于提取不同值的单个正则表达式
- c# - 无法使用应用程序池用户从托管在 IIS 上的 Web API 打开 kerberos 连接
- java - 使用 GSON 的 JSON 异常
- android - 错误的魔法值:尝试使用 fork 运行 UI 测试时为 64 65 78 0a 30 33 37 00
- elasticsearch - 对来自 elasticsearch 的分组结果进行分组