Postgres:使用Django查询JSON键的值 [英] Postgres: values query on json key with django
问题描述
我需要在Django 1.10
中对postgres支持的jsonfield上的嵌套键执行value / values_list查询。
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.JSONField()
如果其值如下:
{
'lev1': {
'lev': 2
}
}
我想运行类似的查询
AbcModel.objects.values('context__lev1__lev2').distinct()
AbcModel.objects.values_list('context__lev1__lev2', flat=True).distinct()
编辑:JSON字段是官方的django.contrib.postgres.fields中的django JSONField
The JSON fields are the official django JSONField from django.contrib.postgres.fields
推荐答案
所以我找到了一个解决方案,该解决方案适用于django 1.10及更高版本。
我使用KeyTransform注释并提取了下一个键,并对此做了一个values_list。
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'))
此查询使我可以将lev1和lev2用作模型中的常规字段,因此可以执行一个值,values_list或字段上的任何其他有效查询。
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允许将两个Transforms嵌套在一个带注释的文件中,因为我已升级,所以不确定约1.10的嵌套到1.11
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
这篇关于Postgres:使用Django查询JSON键的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!