使用queryset.extra()(django)按注释计数和日期排序和限制查询集

时间:2010-05-30 12:04:53

标签: python sql mysql django

我正在尝试根据每个对象的注释数量以及发布注释的时间范围对对象的查询集进行排序/缩小。我使用queryset.extra()方法(使用django_comments使用通用外键)。

我有了使用queryset.extra()(和代码)from here的想法。这是my initial question yesterday的后续问题(显示我正在取得一些进展)。

当前代码:

到目前为止我所做的工作是根据评论的数量排序;但是,我想扩展功能,并且能够传递时间范围参数(例如,7天)并返回该时间范围内评论最多的帖子的有序列表。

以下是我的观点与基本功能的完整结合:

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: # this is where I started working on the date business ... 
        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)

我试过的:

我不熟悉SQL,但我确实尝试手动添加另一个WHERE标准,看看我是否可以取得一些进展:

    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'    

但除了我的排序顺序之外,它没有做任何事情。

关于如何添加这个额外功能层的任何想法?

感谢您的帮助或见解。

1 个答案:

答案 0 :(得分:1)

尝试此[已更新以包含时差(cutoff_date)]

 queryset = queryset.extra(select={
            'comment_count' : """
                SELECT COUNT(*)
                FROM django_comments
                WHERE
                    django_comments.content_type_id=%s AND
                    django_comments.object_pk=%s.%s AND
                    django_comments.submit_date < '%s'
            """ % ( ctype.pk, 
                    queryset.model._meta.db_table, 
                    queryset.model._meta.pk.name,
                    cutoff_date ),
            }).order_by('-comment_count', '-created')

为了获得一个好的cutoff_date,我建议使用来自python-dateutil模块的awesome-in-a-box relativedelta:

from datetime import relativedelta
from datetime import date

cutoff_date = date.today() - relativedelta(weeks =1) #relativedelta does all the heavy lifting