Rewrite raw SQL as Django query

大兔子大兔子 提交于 2019-12-06 09:44:01

I guess you want to order by the maximum date so:

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

The following view amalgamates two queries to solve the problem,

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

    return render(request, 'info.html', {'info_model': info_model})
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!