我正在尝试编写这个原始 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