【问题标题】:How to query a JSONField comprising a list of values in DJANGO如何在 DJANGO 中查询包含值列表的 JSONField
【发布时间】:2021-04-18 12:52:27
【问题描述】:

我正在使用JSONField 将配置参数(user_types)存储为如下列表:

["user_type1", "user_type2", "user_type3"]

如何查询过滤类型为“user_type1”的元素?以下查询无效:

rows=ConfigUserTable.objects.filter(user_types__in=["user_type1"])

谢谢

【问题讨论】:

  • 您使用的是哪个数据库后端?

标签: python json django orm django-jsonfield


【解决方案1】:

使用contains 查找,它被JSONField 覆盖。例如,以下可能有效:

ConfigUserTable.objects.filter(user_types__contains="user_type1")

但是,这可能取决于您在字段中存储 JSON 数据的方式。如果您将数据存储为字典,那么查询该键肯定会起作用。 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

【讨论】:

    猜你喜欢
    • 2017-02-21
    • 2019-03-22
    • 1970-01-01
    • 2021-09-23
    • 1970-01-01
    • 1970-01-01
    • 2011-06-17
    • 2018-10-19
    • 1970-01-01
    相关资源
    最近更新 更多