2012-12-24 118 views
1

我希望在django上做類似SQL的「Group by,Count」。這裏是我當前的代碼的進展:Django註釋問題

tags = tag.objects.values('tag').annotate(Count('tag')).order_by() 

班標籤:

class tag(models.Model): 
    id = models.IntegerField('id',primary_key=True,null=False) 
    question_id = models.ForeignKey(question,null=False) 
    tag = models.TextField('tag',null=True) 

所以,我的問題是上面的查詢是否能夠獲得可能類似於SQL的「分組依據,計數」?如果是,我應該如何獲得計數值?

+0

您正在使用'Count'上'文字field'爲什麼? –

回答

1

您可以將註釋值:

tags = tag.objects.values('tag').annotate(tag_count=Count('tag')).order_by() 
for tag in tags: 
    print tag['tag_count'] 

你也可以在你的order_by使用註釋值:

tags = tag.objects.values('tag').annotate(tag_count=Count('tag')).order_by('-tag_count') 
+0

嗯,爲什麼我的「tag.tag_count」給出錯誤? - >'dict'對象沒有任何屬性'tag_count' – jdtoh

+0

哦,抱歉,由於'group by'嘗試'tag ['tag_count']' –

+0

謝謝!有用! – jdtoh