我有以下数据,
该查询按 topicid 分组,然后在每个组中获取最大日期、帖子频率并计算作为贡献者的作者数量,
info_model = InfoModel.objects.values('topicid')
.annotate( max=Max('date'), freq=Count('postid'),
contributors=Count('author', distinct=True))
该查询可以显示如下,
Q.1(已解决)如何按日期从最近的时间开始对行进行排序?我确实将 .order_by('date') 附加到查询中,这似乎是最明显的解决方案,但这会产生,
彻底改变‘频率’和‘贡献’。
编辑:排序可以通过附加 .order_by('-max') 来实现
Q.2 如何显示该日期的“帖子”?所以帖子栏应该显示,
ya
see 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>
Thanks,
Edit:
我可以使用原始 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 查询 https://stackoverflow.com/questions/37901376/rewrite-raw-sql-as-django-query