将原始SQL重写为Django查询

时间:2016-06-18 20:31:04

标签: django django-queryset rawsql

我正在尝试编写这个原始SQL查询,

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

作为django查询。以下尝试不起作用,因为我无法获得“作者”和“发布”的相关字段。

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

使用原始SQL我可以使用SELECT *但是如何使用Django查询执行等效操作?

模型是,

class InfoModel(models.Model):
    topicid = models.IntegerField(default=0)
    postid = models.IntegerField(default=0)
    author = models.CharField(max_length=30)
    post = models.CharField(max_length=30)
    date = models.DateTimeField('date published')

我之前在Django Using order_by with .annotate() and getting related field

发布了此问题

2 个答案:

答案 0 :(得分:3)

我想你想按照最长日期订购:

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

答案 1 :(得分:0)

以下视图合并了两个查询来解决问题,

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