Postgres: values query on json key with django

后端 未结 2 1364
心在旅途
心在旅途 2021-01-04 07:10

I need to do a values/values_list query on nested key on a postgres backed jsonfield in django 1.10 eg.

class AbcModel(models.model):
    context = fields.JS         


        
2条回答
  •  爱一瞬间的悲伤
    2021-01-04 07:28

    So I found a solution, this works with django 1.10 and above. I used the KeyTransform to annotate and extract the nexted key and did a values_list on that.

    from django.contrib.postgres.fields.jsonb import KeyTransform
    extracted_query = AbcModel.objects.annotate(lev1=KeyTransform('lev1', 'context')).annotate(lev2=KeyTransform('lev', 'lev1'))
    

    This query allows me to use lev1 and lev2 as normal fields in the model, so I can do a values, values_list or any other valid query on the fields.

    Django 1.11 allows to nest the the two Transforms in one annotate, not sure about 1.10 about the nesting as I have upgraded to 1.11

提交回复
热议问题