Django filter JSONField list of dicts

前端 未结 3 1143
盖世英雄少女心
盖世英雄少女心 2020-12-03 21:31

I run Django 1.9 with the new JSONField and have the following Test model :

class Test(TimeStampedModel):
    actions = JSONField()

Let\'s

3条回答
  •  佛祖请我去吃肉
    2020-12-03 21:46

    If you wan't to filter your data by one of fields in your array of dicts, you can try this query:

    Test.objects.filter(actions__contains=[{'fixed_key_1': 'foo2'}])
    

    It will list all Test objects that have at least one object in actions field that contains key fixed_key_1 of value foo2.

    Also it should work for nested lookup, even if you don't know actual indexes:

    Test(actions=[
        {'fixed_key_1': 'foo4', 'fixed_key_3': [
            {'key1': 'foo2'},
        ]}
    }).save()
    
    Test.objects.filter(actions__contains=[{'fixed_key_3': [{'key1': 'foo2'}]}])
    

    In simple words, contains will ignore everything else.

    Unfortunately, if nested element is an object, you must know key name. Lookup by value won't work in that case.

提交回复
热议问题