2010-03-25 63 views
0

我有以下型號:Django - 通過ForeignKey值的總和排序過濾器?

class User: 
    name = models.CharField(max_length = 200) 
    problem_user = models.BooleanField(default=False) 
    def points_total(self): 
     points_added = PointsAdded.objects.filter(user=self) 
     points_total = 0 
     for point in points_added: 
      points_total += point.points 
     return points_total 

class PointsAdded: 
    points = models.IntegerField() 
    user = models.ForeignKey(User) 

我想回報廣大用戶對他們來說,problem_user是假,由points_total字段排序列表。

我知道我需要使用註釋(如described here),但我是一個新手,並不真正知道如何使用它,因爲這個例子與我的情況稍有不同。這不起作用:

leaders = VideoUser.objects.filter(problem_user=False).pointsadded_set. \ 
       .annotate(points_total=Sum('points__value')) \ 
       .order_by('points_total') 

替代似乎是寫出來了我的整個points_total功能的上述表達的註釋()段內 - 這可能嗎?

有沒有辦法達到我想要使用Django的功能做或我必須退回到SQL?或者我應該重新設計我的數據庫:)

回答

0

你不需要pointsadded_set。如果我正確理解你的模型,這應該工作:

VideoUser.objects.filter(problem_user=False) \ 
      .annotate(points_total=Sum('pointsadded__points__value')) \ 
      .order_by('points_total') 
+0

不幸的是,這會在第二行產生一個SyntaxError。我也嘗試過使用Sum('points'),但那也給了一個SyntaxError。讓我知道你是否想要完整的回溯。 – AP257 2010-03-25 19:01:56

+0

對不起,留下了一個額外的點。現在嘗試。 – 2010-03-25 20:13:03

+0

仍然沒有運氣,抱歉:(這給了我「FieldError在/排行榜/ 無法解析關鍵字‘點’到外地的選擇是:」,然後從用戶字段的字段列表看起來它不知道。它應該使用PointsAdded字段...? – AP257 2010-03-26 11:20:39