查询django postgres嵌套jsonfield

时间:2019-06-28 19:36:23

标签: django postgresql django-models

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'])开始无效。

1 个答案:

答案 0 :(得分:0)

执行此操作的一种可能方法是,使用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)