Django使用.order_by()和.annotate()获取相关字段

3

我有以下数据,

enter image description here

这个查询按主题id分组,然后在每个组中获取最大日期、帖子频率和作者数量作为贡献者。
    info_model = InfoModel.objects.values('topicid')
            .annotate( max=Max('date'), freq=Count('postid'),                   
             contributors=Count('author', distinct=True))

此查询可以如下显示,

enter image description here

问题1(已解决):我如何按日期从最近到最远排序行?我在查询中添加了.order_by('date'),这似乎是最明显的解决方案,但这会产生以下结果:

enter image description here

完全更改“freq”和“contributions”的内容。

编辑:可以通过附加.order_by('-max')来实现排序。

问题2 如何显示该日期的“post”? 因此,帖子列应显示,

ya

见你

ciao

yoyo

我认为以下内容应与{{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'))

我将这个问题简化并重新发布在这里 将原始SQL重写为Django查询


我在这里写了一个解决方案 http://stackoverflow.com/questions/37908049/get-related-column-on-annotate-data-django/37911943#37911943 - Shane G
1个回答

2
以下视图合并了两个查询以解决问题,
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})

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接