获取.annotate()数据Django上的相关列 [英] Get related column on .annotate() data Django
问题描述
我需要通过topicid对上面的数据进行分组,找到每个组的最大日期,然后获取该日期的作者。
$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ b $
在模板中迭代,
< table>
{%for info in info%}
< tr>
< td> {{item.topicid}}< / td>
< td> {{item.max}}< / td>
< td> {{item.author}}< / td>
< / tr>
{%endfor%}
< / table>
生成
如何显示每个最大日期的作者列?
我可以用这样的原始sql查询来执行此操作,
info = list(TempModel.objects
.raw('SELECT *,max(date)AS max
FROM crudapp_tempmodel
GROUP BY topicid
ORDER BY date DESC'))
但是我想使用Django查询来执行。
我正在寻找的输出是
如果这不可能与Django查询我想知道。
谢谢,
解决方案是合并另一个查询,将一个查询的日期与另一个查询的最大值进行比较。
这样做,
def temp(request):
info2 = TempModel.objects.all()
info = TempMod el.objects
.values('topic')
.annotate(max = Max('date'))
.order_by(' - max')
columnlist = []
在info2中的项目:
columnlist.append([item])
在info中的项目
for i in range(len(columnlist ))
如果item ['max'] == columnlist [i] [0] .date:
item ['author'] = columnlist [i] [0] .author
return render(request,'template.html',{'info':info,'info2':info2})
I created this simple set of data to illustrate my point. It is a simple model with no further relations to any other model.
I need to group the data above by topicid, find the max date for each group and then get the author for that date.
info = TempModel.objects
.values('topic')
.annotate( max=Max('date'))
.order_by('-max')
Iterating through this in a template,
<table>
{% for item in info %}
<tr>
<td>{{ item.topicid }}</td>
<td>{{ item.max }}</td>
<td>{{ item.author }}</td>
</tr>
{% endfor %}
</table>
produces,
How do I display the 'author' column for each max date?
I can do this with a raw sql query like this,
info = list(TempModel.objects
.raw('SELECT *, max(date) AS max
FROM crudapp_tempmodel
GROUP BY topicid
ORDER BY date DESC'))
But I want to do it using a Django query.
The output I am looking for is,
If this is not possible with a Django query I would like to know.
Thanks,
A solution is to amalgamate another query which compares date from one query with max from the other.
Here is the view that does this,
def temp(request):
info2 = TempModel.objects.all()
info = TempModel.objects
.values('topic')
.annotate( max=Max('date'))
.order_by('-max')
columnlist = []
for item in info2:
columnlist.append([item])
for item in info:
for i in range(len(columnlist)):
if item['max'] == columnlist[i][0].date:
item['author'] = columnlist[i][0].author
return render(request, 'template.html', {'info': info, 'info2': info2})
这篇关于获取.annotate()数据Django上的相关列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!