【问题标题】:Query django postgres nested jsonfield查询 django postgres 嵌套的 jsonfield
【发布时间】:2019-06-28 19:36:23
【问题描述】:
from django.contrib.postgres.fields import JSONField
class Entity(Model):
    lang = CharField()
    data = JSONField()

如何查询此模型以查找包含给定值的所有对象。 JSON 可以嵌套。

例如,如果data

[
{
   'name': 'Alfred',
   'children': [{'name': 'Bob', 'children':['name': 'Melanie']}] 
},
{
   'name': 'Harry',
   'children': [{'name': 'Helen'}] 
}
]

如果我搜索Melanie,我想返回它。可以有任何级别的嵌套。

来自文档Entity.objects.filter(data__values__contains=['Melanie']) 不起作用。

【问题讨论】:

    标签: django postgresql django-models


    【解决方案1】:

    一种可能的方法是,使用 while 循环检查每个级别,直到找不到子级:

    children = 'data__children'
    results = {}
    while children:
        try:
            # does the children array have anything on this iteration?
            # data__children__exists
            # data__children__data__children__exists
            # and so on
    
            items = Entity.objects.filter(**{f"{children}__exists": True})
            if not len(items):
                 children = None
    
            # filter for "data__children__name__icontains"
            # "data__children__children__name__icontains"
            # and so on for each loop
    
            f = {"{children}__name__icontains": "melanie"}
    
            # add the filtered names
            results.update({children: Entity.objects.filter(*f)})
    
            children += '__data__children'
            # or possibly "__children" here ???
            # just how arbitrary are the recursion keys?
        except:
            children = None
    print(results)
    

    【讨论】:

    • 如果我有任意的json结构怎么办?
    • 不知道孩子们能达到什么水平。
    • @AndrewFount 我明白了,更新了。这对你有意义吗?
    • 如果我有 {'name': 'Alfred', 'data': [[{'name': 'John', 'children': ['name': 'Melanie']} ]]} ?
    • @AndrewFount 那么递归键到底是什么样的?类似obj.data.children.data.children.data.children.data.children.data.children...?
    猜你喜欢
    • 2018-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-28
    • 2021-11-30
    • 2022-11-30
    • 1970-01-01
    • 2023-04-07
    相关资源
    最近更新 更多