http://github.com/coleifer/django-generic-aggregation
http://charlesleifer.com/blog/generating-aggregate-data-across-generic-relations/
Generate and calculate aggregations across generic foreign keys.
>>> from misc import generic_annotate, generic_aggregate
>>> from blog.models import Entry
>>> from tagging.models import TaggedItem
>>> from django.db.models import Count
>>> qs = generic_annotate(Entry.objects.all(), TaggedItem.object, 'id', Count)
>>> qs[0].score
5L
>>> qs[1].score
4L
>>> qs[1].tags
u'databases django many-to-many python'
>>> generic_aggregate(Entry.objects.all(), TaggedItem.object, 'id', Count)
106L # total number of times entries were tagged
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 | from django.contrib.contenttypes.models import ContentType
from django.db import connection, models
def generic_annotate(queryset, gfk_field, aggregate_field, aggregator=models.Sum, desc=True):
ordering = desc and '-score' or 'score'
content_type = ContentType.objects.get_for_model(queryset.model)
qn = connection.ops.quote_name
# collect the params we'll be using
params = (
aggregator.name, # the function that's doing the aggregation
qn(aggregate_field), # the field containing the value to aggregate
qn(gfk_field.model._meta.db_table), # table holding gfk'd item info
qn(gfk_field.ct_field + '_id'), # the content_type field on the GFK
content_type.pk, # the content_type id we need to match
qn(gfk_field.fk_field), # the object_id field on the GFK
qn(queryset.model._meta.db_table), # the table and pk from the main
qn(queryset.model._meta.pk.name) # part of the query
)
extra = """
SELECT %s(%s) AS aggregate_score
FROM %s
WHERE
%s=%s AND
%s=%s.%s
""" % params
queryset = queryset.extra(select={
'score': extra
},
order_by=[ordering])
return queryset
def generic_aggregate(queryset, gfk_field, aggregate_field, aggregator=models.Sum):
content_type = ContentType.objects.get_for_model(queryset.model)
queryset = queryset.values_list('pk') # just the pks
inner_query, inner_params = queryset.query.as_nested_sql()
qn = connection.ops.quote_name
# collect the params we'll be using
params = (
aggregator.name, # the function that's doing the aggregation
qn(aggregate_field), # the field containing the value to aggregate
qn(gfk_field.model._meta.db_table), # table holding gfk'd item info
qn(gfk_field.ct_field + '_id'), # the content_type field on the GFK
content_type.pk, # the content_type id we need to match
qn(gfk_field.fk_field), # the object_id field on the GFK
)
query_start = """
SELECT %s(%s) AS aggregate_score
FROM %s
WHERE
%s=%s AND
%s IN (
""" % params
query_end = ")"
# pass in the inner_query unmodified as we will use the cursor to handle
# quoting the inner parameters correctly
query = query_start + inner_query + query_end
cursor = connection.cursor()
cursor.execute(query, inner_params)
row = cursor.fetchone()
return row[0]
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 6 months ago
Comments
Please login first before commenting.