Permalink
Browse files

abstracted out queryset logic for top_objects to a function

  • Loading branch information...
1 parent d82da8d commit 13b5f8b8228b7bc8b63c076b3e3f9809d6440f02 @paltman paltman committed Feb 3, 2011
Showing with 37 additions and 30 deletions.
  1. +30 −0 agon/models.py
  2. +7 −30 agon/templatetags/agon_tags.py
View
30 agon/models.py
@@ -233,3 +233,33 @@ def points_awarded(target, since=None):
).filter(
timestamp__gte=since
).aggregate(models.Sum("points")).get("points__sum", 0)
+
+
+def get_top_objects(model, limit, time_limit):
+ queryset = model.objects.all()
+
+ if time_limit is None:
+ if issubclass(model, User):
+ queryset = queryset.annotate(
+ num_points=models.Sum("targetstat_targets__points")
+ )
+ else:
+ raise NotImplementedError("Only auth.User is supported at this time.")
+ else:
+ since = datetime.datetime.now() - time_limit
+ if issubclass(model, User):
+ queryset = queryset.filter(
+ awardedpointvalue_targets__timestamp__gte=since
+ ).annotate(
+ num_points=models.Sum("awardedpointvalue_targets__points")
+ )
+ else:
+ raise NotImplementedError("Only auth.User is supported at this time.")
+
+ queryset = queryset.filter(num_points__isnull=False).order_by("-num_points")
+
+ if limit is not None:
+ queryset = queryset[:limit]
+
+ return queryset
+
View
37 agon/templatetags/agon_tags.py
@@ -1,12 +1,9 @@
import datetime
from django import template
-from django.db.models import Sum
from django.db.models.loading import cache as app_cache
-from django.contrib.auth.models import User
-
-from agon.models import points_awarded
+from agon.models import points_awarded, get_top_objects
register = template.Library()
@@ -91,35 +88,15 @@ def render(self, context):
if model is None:
raise incorrect_value
- queryset = model.objects.all()
-
- if self.time_limit is None:
- if issubclass(model, User):
- queryset = queryset.annotate(
- num_points=Sum("targetstat_targets__points")
- )
- else:
- raise NotImplementedError("Only auth.User is supported at this time.")
- else:
- since = datetime.datetime.now() - self.time_limit
- if issubclass(model, User):
- queryset = queryset.filter(
- awardedpointvalue_targets__timestamp__gte=since
- ).annotate(
- num_points=Sum("awardedpointvalue_targets__points")
- )
- else:
- raise NotImplementedError("Only auth.User is supported at this time.")
-
- queryset = queryset.filter(
- num_points__isnull=False
- ).order_by("-num_points")
-
if self.limit is not None:
limit = self.limit.resolve(context)
- queryset = queryset[:limit]
- context[self.context_var] = queryset
+ context[self.context_var] = get_top_objects(
+ model,
+ limit,
+ self.time_limit
+ )
+
return u""

0 comments on commit 13b5f8b

Please sign in to comment.