Django使用带有.annotate()的order_by并获取相关字段

时间:2016-06-17 22:26:20

标签: sql-order-by django-queryset annotate

我有以下数据,

enter image description here

此查询按topicid分组,然后在每个组中获取帖子的最大日期,频率并计算作者的贡献者数量,

    info_model = InfoModel.objects.values('topicid')
            .annotate( max=Max('date'), freq=Count('postid'),                   
             contributors=Count('author', distinct=True))

此查询可以显示如下,

enter image description here

Q.1(已解决)如何从最近的日期开始按日期订购行?我在查询中添加了.order_by(' date'),这似乎是最明显的解决方案,但这会产生,

enter image description here

完全改变了频率'和#'贡献'。

编辑:可以通过附加.order_by(' -max')来实现订购

Q.2如何显示'帖子'那个日期?所以post列应该显示,

见ya

溜溜球

我认为以下内容适用于{{item.post}},但没有运气。

  <table class='table table-striped table-hover'>
        <thead>
          <tr>
            <th>freq</th>
            <th>topicid</th>
            <th>date</th>
            <th>contributors</th>
            <th>post</th>
          </tr>
        </thead>
        <tbody>
          {% for item in info %}
          <tr>
            <td>{{ item.freq }}</td>
            <td>{{ item.topicid }}</td>
            <td>{{ item.max }}</td>
            <td>{{ item.contributors }}</td>
            <td>{{ item.post }}</td>
          </tr>
          {% endfor %}
        </tbody>
      </table>

谢谢,

编辑:

我可以使用原始SQL获得正确的结果,但不能使用Django查询,

info_model = list(InfoModel.objects.raw('SELECT *, 
              max(date),  
              count(postid) AS freq,     
              count(DISTINCT author) AS contributors FROM        
              crudapp_infomodel GROUP BY topicid ORDER BY date DESC'))

我在此处简化并重新发布此问题Rewrite raw SQL as Django query

1 个答案:

答案 0 :(得分:1)

以下视图合并了两个查询来解决问题,

def info(request):
    info_model = InfoModel.objects.values('topic')
                 .annotate( max=Max('date'), 
                 freq=Count('postid'), 
                 contributors=Count('author', distinct=True))
                 .order_by('-max')

    info2 = InfoModel.objects.all()

    columnlist = []
    for item in info2:
         columnlist.append([item])

    for item in info_model:
        for i in range(len(columnlist)):
            if item['max'] == columnlist[i][0].date:
                item['author'] = columnlist[i][0].author
                item['post'] = columnlist[i][0].post
                print item['max']

    paginator = Paginator(info_model, 20)
    page = request.GET.get('page')
    try:
        info = paginator.page(page)
    except PageNotAnInteger:
        # If page is not an integer, deliver first page.
        info = paginator.page(1)
    except EmptyPage:
        # If page is out of range (e.g. 9999), deliver last page of results.
        info = paginator.page(paginator.num_pages)
    return render(request, 'info.html', {'info': info})