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:

  1. id: 1, data = {'aa': 1, 'bb': 2, 'cc':4}
  2. id: 2, data = {'aa': 3, 'bb': 2}
  3. id: 3, data = {'cc': 7}
  4. 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:

  1. id: 3
  2. id: 1
  3. id: 2
  4. 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

Popular posts from this blog

html - How to set bootstrap input responsive width? -

javascript - Highchart x and y axes data from json -

javascript - Get js console.log as python variable in QWebView pyqt -