将原始 SQL 重写为 Django 查询

Rewrite raw SQL as Django query

我正在尝试编写这个原始 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 查询。以下尝试不起作用,因为我无法获得 'author' 和 'post'.

的相关字段
  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')

我以前post这里有这个问题

我猜你想在最大日期前订购所以:

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

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

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