2016-06-18 40 views
2

我想寫這個原始的SQL查詢,重寫原始的SQL作爲Django的查詢

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

+1

我想你正在使用MySQL,因爲你的原始查詢不能在PostGres上運行。原因是你訂購的產品不屬於團隊。你的原始查詢很奇怪,請提供一個輸入和一個預期的輸出 –

+0

好吧,我明白你的意思了,所以我需要使用.order_by(' - max')。這會正確地排序數據。如果您按照帖子底部的鏈接,您實際上可以看到原始數據。 –

+0

我正在使用sqlite。 –

回答

3

我想你想的最大日期,以便訂購:

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

那order_by(' - max')正常工作,謝謝。但是我不能像SQL那樣顯示其他相關的字段(或者它可能是mySQL,我幾乎不知道其中的差別)。 –

+0

我在這裏寫了一個解決方案http://stackoverflow.com/questions/37908049/get-related-column-on-annotate-data-django/37911943#37911943 –

0

以下視圖amalgamates兩個查詢來解決問題,

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