django orm group by json key in json field

[英]django orm group by json key in json field


I'm using json field on my django model:

我在我的django模型上使用json字段:

class JsonTable(models.Model):
    data = JSONField()
    type = models.IntegerField()

I tried next query, which works for normal sql fields:

我尝试了下一个查询,它适用于普通的sql字段:

JsonTable.objects.filter(type=1).values('type').annotate(Avg('data__superkey'))

But this throws next error:

但这会引发下一个错误:

FieldError: Cannot resolve keyword 'superkey' into field. Join on 'data' not permitted.

Is there way to make group by on json key, using Django ORM or some python lib, without use of raw sql?

有没有办法在json键上使用Django ORM或一些python lib,而不使用原始sql?

Versions: Django 1.9b, PostgreSQL 9.4

版本:Django 1.9b,PostgreSQL 9.4

UPDATE

UPDATE

Example 2:

例2:

JsonTable.objects.filter(type=1).values('data__happykey').annotate(Avg('data_superkey'))

throws same error on happykey

在happykey上抛出相同的错误

2 个解决方案

#1


0  

If you are using this package https://github.com/bradjasper/django-jsonfield, there is nothing in the code for managing such simulated related queries (data__some_json_key) As Json data is text, you will have to go to raw sql or better : use queryset extra() method, but parsing Json in sql seems to be difficult.

如果您使用此程序包https://github.com/bradjasper/django-jsonfield,代码中没有任何内容可用于管理此类模拟相关查询(data__some_json_key)由于Json数据是文本,您将不得不转到原始sql或更好:使用queryset extra()方法,但在sql中解析Json似乎很难。

#2


0  

After some researching I found next solution:

经过一番研究,我找到了下一个解决方案

from django.db.models import Count
from django.contrib.postgres.fields.jsonb import KeyTextTransform

superkey = KeyTextTransform('superkey', 'data')
table_items = JsonTable.objects.annotate(superkey = superkey).values('superkey').annotate(Count('id')).order_by()

I did not sure about order_by(), but documentation says that is needed. For another aggregation function type casting needed:

我不确定order_by(),但文档说这是必要的。对于另一个聚合函数类型转换需要:

from django.db.models import IntegerField
from django.db.models.functions import Cast
superkey = Cast(KeyTextTransform('superkey', 'data'), IntegerField())

I test with another model, hope that write this code without misprints. PostgreSQL 9.6, Django 2.07

我用另一个模型测试,希望编写这些代码而不会出错。 PostgreSQL 9.6,Django 2.07


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.itdaan.com/blog/2015/11/03/751816e5421c35ef243e1fc9decd712e.html



 
© 2014-2018 ITdaan.com 粤ICP备14056181号