Django查询:用*窗口的'count`注释*

时间:2013-09-23 11:56:47

标签: database django django-queryset

我搜索的查询与this one非常相似。但作为一个扩展,我不想计算所有对象,而只是计算那些最近的对象。

就我而言,有两种型号。设一个为Source,一个为Data。结果,我想得到一个列表,列出了上周收集的数据记录数所排序的所有Source。 对我来说,它不是迭代,总共收集了多少数据记录,但是如果该源的最近活动。

使用上面链接中的以下代码段,我无法在子查询之前了解Data表。

from django.db.models import Count
activity_per_source = Source.objects.annotate(count_data_records=Count('Data')) \
            .order_by('-count_data_records')

我提出的唯一方法是编写本机SQL或在循环和单个查询中处理它。有Django-Query版本吗?

(我使用MySQL数据库和Django 1.5.4)

2 个答案:

答案 0 :(得分:1)

按照注释和过滤顺序检出文档:https://docs.djangoproject.com/en/1.5/topics/db/aggregation/#order-of-annotate-and-filter-clauses

尝试以下方面的内容:

activity_per_source = Source.objects.\
    filter(data__date__gte=one_week_ago).\
    annotate(count_data_records=Count('Data')).\
    order_by('-count_data_records').distinct()

答案 1 :(得分:0)

有一种方法可以通过extra

将Django查询与SQL混合
start_date = datetime.date.today() - 7
activity_per_source = (
    Source.objects
    .extra(where=["(select max(date) from app_data where source_id=app_source.id) >= '%s'"
           % start_date.strftime('%Y-%m-%d')])
    .annotate(count_data_records=Count('Data'))
    .order_by('-count_data_records'))

where部分将根据Data上次日期过滤来源。

注意:将表名和字段名替换为实际名称。

相关问题