sql-order-by - Django 在 .annotate() 中使用 order_by 并获取相关字段

标签 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

问题 1(已解决)如何按日期从最近的开始对行进行排序?我确实将 .order_by('date') 附加到查询中,这似乎是最明显的解决方案,但这会产生,

enter image description here

完全改变“频率”和“贡献”。

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

Q.2 如何显示该日期的“帖子”?所以帖子栏应该显示,

是的

再见

再见

悠悠球

我认为以下内容应该适用于 {{ 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

最佳答案

下面的 View 合并了两个查询来解决问题,

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})

关于sql-order-by - Django 在 .annotate() 中使用 order_by 并获取相关字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37891219/

相关文章:

mysql - mysql 记录中字母排序的问题

sql - PostgreSQL 排序依据,数字在后

python - 根据第一个子模型的属性对查询集进行排序,会返回重复的对象。 Django ,DRF

Django - 从每个相册中随机选择一张照片

python - 类型错误 : 'float' object is not iterable trying to annotate an arrow from a list

Mysql Order by query 与 keping track of alphabets

sql - PostgreSQL ORDER BY 列位置(而不是列名)

python - django value_list 给出 id 而不是值

Django:如何基于另一个注解进行注解,或对注解执行操作

java - 与 Java 中的@Override 相反的标记