[Answered ]-Get mean value for price in dict (Django JSONField)

1πŸ‘

βœ…

I did not try it but please give this a try:

from django.db.models import Avg

order_qs = Order.objects.filter(products__contains=[{"sku":"002-2-1"}])
print(order_qs.aggregate(Avg("products__price")))

Interesting resources:
Key, index, and path transforms – how to "deal" with jsonfield lookups
Avg – the function you want to aggregate your queryset with to get the mean value
Conditional Aggregating – general "how-to" how to aggregate with functions like Count or mentioned Avg

Even though you did not ask for a potentially better way I want to say: "Why are you using a JSONField?". In my eyes creating another model called Product and link it via a ForeignKey to Order makes much more sense. It also enables all the cool django features like aggregating, annotating and so much more. Especially if the scheme of the JSONField is always the same… what’s the point in not creating a further model?

I can guarantee you that with a dedicated Product model the provided solution is going to work. With a JSONField I am not 100% sure – let me know!

πŸ‘€Tarquinius

Leave a comment