将原始SQL重写为Django查询 [英] Rewrite raw SQL as Django query
本文介绍了将原始SQL重写为Django查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试编写这个原始的SQL查询,
info_model = list(InfoModel.objects.raw('SELECT * ,
max(date),
count(postid)AS freq,
count(DISTINCT author)AS Contributor FROM
crudapp_infomodel GROUP BY topicid ORDER BY date DESC'))
作为django查询。以下尝试不起作用,因为我无法获取作者和发布的相关字段。
info_model = InfoModel .objects.values('topic')
.annotate(max = Max('date'),
freq = Count('postid'),
贡献者= Count('author'
distinct = True))
.order_by(' - max')
使用原始SQL,我可以使用SELECT *,但是如何使用Django查询执行同样的操作?
模型是
$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
author = models.CharField(max_length = 30)
post = models.CharField(max_length = 30)
date = models.DateTimeField('date published')
我以前在这里发布了这个问题Django使用order_by与.annotate()并获取相关字段
解决方案
我想你想按最高日期排序:
$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ = Count('author',distinct = True)
.order_by('max')
I am trying to write this raw SQL query,
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'))
as a django query. The following attempt does not work as I can't get related fields for 'author' and 'post'.
info_model = InfoModel.objects.values('topic')
.annotate( max=Max('date'),
freq=Count('postid'),
contributors=Count('author',
distinct=True))
.order_by('-max')
With raw SQL I can use SELECT * but how can I do the equivalent with the Django query?
The model is,
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')
I did previously post this problem here Django Using order_by with .annotate() and getting related field
解决方案
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')
这篇关于将原始SQL重写为Django查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文