python data_error ai_generated true

django.core.exceptions.FieldError: Cannot compute Sum('price'): 'price' is an aggregate

ID: python/django-query-annotation-error

Also available as: JSON · Markdown · 中文
80%Fix Rate
82%Confidence
0Evidence
2024-05-17First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.x active

Root Cause

对已聚合的字段再次进行聚合操作

generic

中文

在包含聚合的查询集中再次使用聚合函数,导致嵌套聚合错误

Workarounds

  1. 90% success
    qs.values('category').annotate(total=Sum('price'))
  2. 85% success
    from django.db.models import Subquery; ...

Dead Ends

Common approaches that don't work:

  1. 70% fail

    values()不会重置聚合状态

  2. 60% fail

    aggregate返回字典而非查询集,可能不适用