I have a JSONField in my Order model.
products = models.JSONField()
I need to extract some products from orders with the same SKU number.
orders=Order.objects.filter(products__contains=[{"sku":"002-2-1"}])
for e in orders:
print(e.products)
>>> [{'sku': 002-2-1, 'price': '366.00'}, {'sku': 002-2-1, 'price': '366.00'}] # 2 products in 1 order
>>> [{'sku': 002-2-1, 'price': '366.00'}] # 1 product in the order
How can I Sum the prices? I tried
orders.aggregate(earned_sum=Func(Sum(F("products__contains=[{"price"}]")))
but it don't works.
This is likely one of the many reasons not to use JSON fields in a relational database: it makes queries more complicated.
Normally you make two models
Productand `Order with a many-to-many field in between:we can then determine the price of an
Orders object with, withmy_ordersaQuerySetofOrderobjects:or for a specific sku: