1
說我有一對夫婦的模型,通過一個外鍵關係到另一個像這樣:向後繼關係,並註釋結果
class Tourist(models.Model):
age = models.IntegerField()
class Country(models.Model):
tourist = models.ForeignKey(Tourist)
我知道,我可以從旅遊向後工作找出他一直在使用多少個國家:
t = Tourist.objects.all()[0]
t.country_set.count()
但是有什麼方法可以標註遊客訪問過的國家數嗎?這將是冷靜,如果我可以做類似
Tourist.objects.annotate(countries_visited=country_set.count())
我知道的「代碼」的最後一位也沒有什麼意義,但我指望它來傳達我的心臟的慾望。我知道我可以做這樣的事情:
[(t.pk, t.country_set.count()) for t in Tourist.objects.all()]
但我只是想知道是否有更好的方法來做到這一點。謝謝!
哇,真棒!謝謝微風! – IntrepidDude 2010-12-15 04:38:25