How to aggregate over Django Jsonfield values?

I have a JsonField (col1) in a Model (model1) which contains values like below:

{"key_1":"val_1", "key_2":"{\"sub_key1\":sub_val1, \"sub_key2\":sub_val2}"}

I would like to aggregate sub_key1 and sub_key2. I tried below in Python but it does not work.

from django.db.models import FloatField, JSONField
from django.db.models import Sum, Value
from django.db.models.functions import Cast

## try 1   
model1.objects.annotate(val=Cast('col1__key_2__sub_key1', FloatField())).aggregate(op=Sum('val'))

## try 2
    val=Cast('col1__key1', JSONField())).annotate(
    val_2=Cast('val__sub_key1', FloatField())).aggregate(op=Sum('val_2'))

Is there a way I can aggregate over these sub keys?

Back to Top