python - django - aggregate json field specific keys and order by the aggregation -
have model field data
of type jsonfield
django.contrib.postgres.fields
. json structure so:
{'aa': 1, 'bb': 2, 'cc': 4}
i want aggregate sums of aa
, cc
keys - in case, 5. - cannot promise either aa
or cc
in json.
possible? if - want order aggregated data.
example:
- id: 1, data = {'aa': 1, 'bb': 2, 'cc':4}
- id: 2, data = {'aa': 3, 'bb': 2}
- id: 3, data = {'cc': 7}
- id: 4, data = {'bb': 7}
i want query, like:
mymodel.objects.aggregate(my_sum).order_by(my_sum)
after aggregation ordered rows in queryset be:
- id: 3
- id: 1
- id: 2
- id: 4
thanks!
yourmodel.objects.annotate(aa=rawsql("((data->>'aa')::int)", (0,)), cc=rawsql("((data->>'cc')::int)", (0,))) \ .aggregate(total=sum('aa')+sum('cc')).order_by('total')
Comments
Post a Comment