2012-08-07 35 views
0

我有一個模型的主題如何寫Django模型這個SQL查詢

#models.py 

class Subjects(models.Model) 
    .... 
    name = models.ForeignKey(User, unique=False) 
    .... 
    number_of_followers = models.IntegerField(I want to have something like this: SELECT COUNT(DISTINCT name) FROM school_subjects;) 

我真的不知道,如果我能做到這裏面IntegerField還是我來補充這種保存方法。

預先感謝您。

+1

Django的書有答案種種這些簡單的問題:http://djangobook.com/en/2.0/ – 2012-08-07 00:20:24

回答

2

這樣的事情(使用count())?

Subjects.objects.all().count() 
+0

是的,這是正確的,但如何我可以更新models.py中的number_of_followers?換句話說,當對象被創建時,我希望這個字段是自動的字段。 – Vor 2012-08-07 00:22:17

+0

因此,您想要將不同'Subject'對象的總數保存到每個'Subject'對象的'number_of_followers'字段中?我認爲最好是製作一個可以動態計算的方法 – 2012-08-07 01:11:54

0

試試這個:

school_subjects.objects.all().distinct('name').count()