2009-11-21 32 views
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()功能采取了赎回?

回答

5

原来的标注方法是溶液:

Post.objects.all().annotate(vote_tally=Sum('vote__value')).order_by('-vote_tally') 
+2

顺便说一句,使用'。所有()'是多余 – SmileyChris 2009-11-22 21:53:52

相关问题