3
重複:Using a Django custom model method property in order_by()是否可以用可調用函數order_by?
我有兩個型號;一個存儲帖子,另一個存儲在這些帖子上發表的投票,使用ForeignKey字段相關。由於我需要跟蹤投票投票的用戶和日期時間,每個投票都存儲爲單獨的記錄。
我創建了一個使用Django 1.1聚合Sum函數計算所有選票的幫助函數。
class Post(models.Model):
...some fields...
def tally(self):
return self.vote_set.all().aggregate(Sum('value'))['value__sum'] or 0
class Vote(models.Model):
post = models.ForeignKey(Post)
value = models.IntegerField()
...some fields...
我需要做的一個查詢需要做一個關閉order_by
的理貨。但是:
Post.objects.all().order_by('tally')
產生以下模板錯誤:
Caught an exception while rendering: Cannot resolve keyword 'tally' into field. Choices are: date_created, description, id, is_active, name, related, slug, user, vote
它有什麼辦法讓order_by()
功能採取了贖回?
順便說一句,使用'。所有()'是多餘 – SmileyChris 2009-11-22 21:53:52