#20930: Arithmetic operations on aggregates -------------------------------------+------------------------------------- Reporter: debanshuk | Owner: nobody Type: New feature | Status: new Component: Database layer | Version: master (models, ORM) | Resolution: Severity: Normal | Triage Stage: Keywords: aggregate, annotate | Unreviewed Has patch: 1 | Needs documentation: 0 Needs tests: 0 | Patch needs improvement: 0 Easy pickings: 0 | UI/UX: 0 -------------------------------------+-------------------------------------
Comment (by debanshuk): Hi Wim, In the example given in the description, it would. And I guess in case of aggregates it would always be possible to make the calculations out side aggregate. But, '''in case of annotate it would not'''. Well, it would certainly be possible, but wouldn’t be cleaner, as one would have to do the calculations for each element in resultant query-set. Eg. Let modified `Xyz` be: {{{ class Xyz(models.Model): user = models.ForeignKey(User) a = models.IntegerField() b = models.IntegerField() }}} Now if I want to find find percent ratio of sum of all `a` and sum of all `b` of a `user`, for each `user`. I may write: {{{ Xyz.objects.values('user').annotate(ratio_percent=Sum('a')/Sum('b')*100) }}} Currently, to do this (without writing raw SQL), one would have to do something like: {{{ result = Xyz.objects.values('user').annotate(total_a=Sum('a'), total_b=Sum('b')) final_result = [{'user': r['user'], 'ratio_percent': r['total_a']/r['total_b']*100} for r in result] }}} '''Also''', If someone want to aggregate over annotation results, like in the example if I want to find maximum of the ratio_percentage, I may do: {{{ Xyz.objects.values('user').annotate(ratio_percent=Sum('a')/Sum('b')*100).aggregate(Max('ratio_percent')) }}} Currently, I would have to do: {{{ result = Xyz.objects.values('user').annotate(total_a=Sum('a'), total_b=Sum('b')) final_result = max(r['total_a']/r['total_b']*100 for r in result) }}} '''In the second one, max calculation in done in python. In the first one it is done in SQL itself.''' -- Ticket URL: <https://code.djangoproject.com/ticket/20930#comment:4> Django <https://code.djangoproject.com/> The Web framework for perfectionists with deadlines. -- You received this message because you are subscribed to the Google Groups "Django updates" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-updates+unsubscr...@googlegroups.com. To post to this group, send email to django-updates@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/django-updates/067.19a258787a07d5e5d3d2de7c83ebbab8%40djangoproject.com. For more options, visit https://groups.google.com/groups/opt_out.