Ticket #11256: aggregate-validation.diff

File aggregate-validation.diff, 1.9 KB (added by Alex Gaynor, 14 years ago)
  • django/db/models/query.py

    diff --git a/django/db/models/query.py b/django/db/models/query.py
    index c8e630a..0cc6c49 100644
    a b class QuerySet(object):  
    605605        Return a query set in which the returned objects have been annotated
    606606        with data aggregated from related fields.
    607607        """
     608        total_aggregates = len(args) + len(kwargs)
    608609        for arg in args:
    609610            kwargs[arg.default_alias] = arg
    610611
     612        if len(kwargs) != total_aggregates:
     613            raise ValueError("Some of the aggregates had duplicate aliases, "
     614                "check to make sure none of your aggregates conflict with the "
     615                "default aliases.")
     616
     617        names = set([f.name for f in self.model._meta.fields])
     618        for aggregate in kwargs:
     619            if aggregate in names:
     620                raise ValueError("The %s aggregate conflicts with a field on "
     621                    "the model." % aggregate)
     622
     623
    611624        obj = self._clone()
    612625
    613626        obj._setup_aggregate_query(kwargs.keys())
  • tests/regressiontests/aggregation_regress/models.py

    diff --git a/tests/regressiontests/aggregation_regress/models.py b/tests/regressiontests/aggregation_regress/models.py
    index 7c51cd1..ccbbbe7 100644
    a b Traceback (most recent call last):  
    318318...
    319319FieldError: Cannot compute Avg('mean_age'): 'mean_age' is an aggregate
    320320
     321>>> Book.objects.all().annotate(Avg('authors__age'), authors__age__avg=Avg('authors__age'))
     322Traceback (most recent call last):
     323...
     324ValueError: Some of the aggregates had duplicate aliases, check to make sure none of your aggregates conflict with the default aliases.
     325
     326>>> Author.objects.annotate(age=Avg('friends__age'))
     327Traceback (most recent call last):
     328...
     329ValueError: The age aggregate conflicts with a field on the model.
     330
    321331"""
    322332}
    323333
Back to Top