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

networking - Vagrant-provisioned VirtualBox VM is not reachable from Ubuntu host -

c# - ASP.NET Core - There is already an object named 'AspNetRoles' in the database -

ruby on rails - ArgumentError: Missing host to link to! Please provide the :host parameter, set default_url_options[:host], or set :only_path to true -