Opened 3 years ago

Closed 3 years ago

#19512 closed New feature (wontfix)

Aggregate or Annotaion on previously Annotated values

Reported by: eye-see-you@… Owned by: nobody
Component: Database layer (models, ORM) Version: 1.4
Severity: Normal Keywords: django, annotate, aggregate
Cc: Triage Stage: Design decision needed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description (last modified by aaugustin)

from django.db.models import Count, Sum, F

myModel.objects \
               .annotate(a_count=Count('field_a'), b_count=Count('field_b')) \
               .annotate(total=F('a_count')+F('b_count')) \

This query is going to raise AttributeError: 'ExpressionNode' object has no attribute 'split'

I don't find any method in django ORM to support such kind of operations (in which two fields are involved).

Change History (3)

comment:1 Changed 3 years ago by anonymous

  • Needs documentation unset
  • Needs tests unset
  • Patch needs improvement unset

Instead of using .extra

myModel.objects.extra(select={'total': 'Count(field_a)+Count(field_b)'})

The method which I don't want to use because its not cool(violation of ORM concept).

comment:2 Changed 3 years ago by aaugustin

  • Description modified (diff)
  • Triage Stage changed from Unreviewed to Design decision needed
  • Type changed from Uncategorized to New feature

The ORM isn't intended to be a complete abstraction to SQL; it's just a shortcut for the most common queries. Dropping to raw SQL (or .extra if you really need to) isn't a violation of the ORM concept; it's part of the ORM concept — at least, as understood in Django.

The docs talk about aggregating annotations, but not about re-annotating annotations. I'm not sure it's possible to support it while keeping the code complexity under control.

comment:3 Changed 3 years ago by aaugustin

  • Resolution set to wontfix
  • Status changed from new to closed

If someone has a good patch for this, why not, but at the moment there isn't one.

Note: See TracTickets for help on using tickets.
Back to Top