Ticket #10929: 10929-aggregates-default-r17029.diff

File 10929-aggregates-default-r17029.diff, 2.2 KB (added by Tai Lee, 13 years ago)
  • tests/modeltests/aggregation/tests.py

     
    565565                (Decimal('82.8'), 1),
    566566            ]
    567567        )
     568
     569    def test_default(self):
     570        p = Publisher.objects.create(name='publisher', num_awards=0)
     571        # return None if there's no default and no data to aggregate.
     572        publisher = Publisher.objects.annotate(avg_book_rating=Avg("book__rating")).get(pk=p.pk)
     573        self.assertEqual(publisher.avg_book_rating, None)
     574        # return the default if one is specified and no data to aggregate.
     575        publisher = Publisher.objects.annotate(avg_book_rating=Avg("book__rating", 0)).get(pk=p.pk)
     576        self.assertEqual(publisher.avg_book_rating, 0.0)
  • django/db/models/sql/aggregates.py

     
    8989        }
    9090        params.update(self.extra)
    9191
    92         return self.sql_template % params
     92        template = self.sql_template
     93        if 'default' in params:
     94            template = 'COALESCE(%s, %%(default)s)' % template
    9395
     96        return template % params
    9497
     98
    9599class Avg(Aggregate):
    96100    is_computed = True
    97101    sql_function = 'AVG'
  • django/db/models/aggregates.py

     
    66    """
    77    Default Aggregate definition.
    88    """
    9     def __init__(self, lookup, **extra):
     9    def __init__(self, lookup, default=None, **extra):
    1010        """Instantiate a new aggregate.
    1111
    1212         * lookup is the field on which the aggregate operates.
     
    1616        Also utilizes the class variables:
    1717         * name, the identifier for this aggregate function.
    1818        """
     19        if default is not None:
     20            extra.setdefault('default', default)
    1921        self.lookup = lookup
    2022        self.extra = extra
    2123
Back to Top