I am trying to sort / narrow the set of requests for objects based on the number of comments that each object has, as well as the timeframe during which the comments were sent. I use a method queryset.extra()(using django_commentsone that uses shared foreign keys).
I got the idea to use queryset.extra()(and code) here . This is the next question from my initial question yesterday (which shows that I'm moving forward).
Current code:
What I still work is that it will sort by the number of comments; however, I want to expand the functionality, and also be able to pass the argument of the time interval (for example, 7 days) and return an ordered list of the most comments in this time frame.
Here's what my view looks like with basic functionality in tact:
import datetime
from django.contrib.comments.models import Comment
from django.contrib.contenttypes.models import ContentType
from django.db.models import Count, Sum
from django.views.generic.list_detail import object_list
def custom_object_list(request, queryset, *args, **kwargs):
'''Extending the list_detail.object_list to allow some sorting.
Example: http://example.com/video?sort_by=comments&days=7
Would get a list of the videos sorted by most comments in the
last seven days.
'''
try:
days = int(request.GET.get('days', None))
period = datetime.datetime.utcnow() - datetime.timedelta(days=int(days))
except (ValueError, TypeError):
days = None
period = None
sort_by = request.GET.get('sort_by', None)
ctype = ContentType.objects.get_for_model(queryset.model)
if sort_by == 'comments':
queryset = queryset.extra(select={
'count' : """
SELECT COUNT(*) AS comment_count
FROM django_comments
WHERE
content_type_id=%s AND
object_pk=%s.%s
""" % ( ctype.pk, queryset.model._meta.db_table,
queryset.model._meta.pk.name ),
},
order_by=['-count']).order_by('-count', '-created')
return object_list(request, queryset, *args, **kwargs)
What I tried:
I am not good at SQL, but I tried just adding one more criterion WHEREto find out if I can make some progress:
SELECT COUNT(*) AS comment_count
FROM django_comments
WHERE
content_type_id=%s AND
object_pk=%s.%s AND
submit_date='2010-05-01 12:00:00'
But it did nothing but mess with my sort order.
Any ideas on how I can add this extra level of functionality?
Thanks for any help or insight.