Skip to content

Commit

Permalink
Allow an alias to be used for the extra param
Browse files Browse the repository at this point in the history
  • Loading branch information
coleifer committed Jun 14, 2010
1 parent d9135d5 commit 1479517
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 5 deletions.
4 changes: 2 additions & 2 deletions generic_aggregation/tests/settings.py
@@ -1,6 +1,6 @@
DATABASE_ENGINE = 'sqlite3'
DATABASE_ENGINE = 'postgresql_psycopg2'
DATABASE_NAME = 'test_main'
#DATABASE_ENGINE = 'postgresql_psycopg2'
#DATABASE_NAME = 'test_main'

INSTALLED_APPS = [
'django.contrib.contenttypes',
Expand Down
14 changes: 14 additions & 0 deletions generic_aggregation/tests/tests.py
Expand Up @@ -121,3 +121,17 @@ def test_charfield_pks(self):

aggregated = generic_aggregate(Food.objects.all(), CharFieldGFK.content_object, 'name', models.Count)
self.assertEqual(aggregated, 3)

def test_custom_alias(self):
annotated_qs = generic_annotate(Food.objects.all(), Rating.content_object, 'rating', models.Count, alias='count')
food_a, food_b = annotated_qs

self.assertEqual(food_a.count, 4)
self.assertEqual(food_a.name, 'apple')

def test_ascending_order(self):
annotated_qs = generic_annotate(Food.objects.all(), Rating.content_object, 'rating', models.Count, desc=False, alias='count')
food_a, food_b = annotated_qs

self.assertEqual(food_b.count, 4)
self.assertEqual(food_b.name, 'apple')
6 changes: 3 additions & 3 deletions generic_aggregation/utils.py
Expand Up @@ -34,8 +34,8 @@ def gfk_expression(qs_model, gfk_field):


def generic_annotate(queryset, gfk_field, aggregate_field, aggregator=models.Sum,
generic_queryset=None, desc=True):
ordering = desc and '-score' or 'score'
generic_queryset=None, desc=True, alias='score'):
ordering = desc and '-%s' % alias or alias
content_type = ContentType.objects.get_for_model(queryset.model)

qn = connection.ops.quote_name
Expand Down Expand Up @@ -76,7 +76,7 @@ def generic_annotate(queryset, gfk_field, aggregate_field, aggregator=models.Sum
inner_query_params = []

queryset = queryset.extra(
select={'score': extra},
select={alias: extra},
select_params=inner_query_params,
order_by=[ordering]
)
Expand Down

0 comments on commit 1479517

Please sign in to comment.