我使用 JSONField
将配置参数(user_types)存储为如下列表:
["user_type1", "user_type2", "user_type3"]
如何查询过滤“user_type1”类型的元素?以下查询无效:
rows=ConfigUserTable.objects.filter(user_types__in=["user_type1"])
谢谢
答案 0 :(得分:0)
使用 contains
查找,它在 JSONField
上被覆盖。例如,以下可能有效:
ConfigUserTable.objects.filter(user_types__contains="user_type1")
但是,这可能取决于您在字段中存储 JSON 数据的方式。如果您将数据存储为 dict,则查询该键肯定会起作用。 IE。字段 user_types
:
{"types": ["user_type1", "user_type2", "user_type3"]}
可以这样查询:
ConfigUserTable.objects.filter(user_types__types__contains="user_type1")
参考:https://docs.djangoproject.com/en/dev/topics/db/queries/#std:fieldlookup-jsonfield.contains