Django JSONField filtering

前端 未结 1 592
后悔当初
后悔当初 2020-12-15 17:58

I\'m using PostgreSQL and this new field from Django 1.9, JSONField. So I got the following data:

id|data
1 |[{\'animal\': \'cat\', \'name\': \'tom\'}, {\'an         


        
相关标签:
1条回答
  • 2020-12-15 18:20

    As per the django JSONField docs, it explains that that the data structure matches python native format, with a slightly different approach when querying.

    If you know the structure of the JSON, you can also filter on keys as if they were related fields:

    object.filter(data__animal='cat')
    object.filter(data__name='tom')
    

    By array access:

    object.filter(data__0__animal='cat')
    

    Your contains example is almost correct, but your data is in a list and requires:

    object.filter(data__contains=[{'animal': 'cat'}])
    
    0 讨论(0)
提交回复
热议问题