2012-03-09 152 views
5

我只想在特定夾具中顯示與團隊相關的球員。通常當我這樣做時,它會向我展示數據庫中的所有玩家。這裏是我的models.pyformfield_for_foreignkey和內聯管理員

class InningsCard(models.Model): 
    fixture = models.ForeignKey(Fixture) 
    team = models.ForeignKey(Team) 
    runs = models.IntegerField(max_length=6, default=0) 
    wickets = models.IntegerField(max_length=6, default=0) 
    overs = models.FloatField(max_length=6, default=0.0) 

    def __unicode__(self): 
     return str(self.team) 

class BattingDetail(models.Model): 
    STATUS_CHOICES = (
     ('no', 'not out'), 
     ('bowled', 'bowled'), 
     ('caught', 'caught'), 
     ('lbw', 'lbw'), 
    ) 
    innings = models.ForeignKey(InningsCard) 
    player = models.ForeignKey(Player) 
    runs = models.IntegerField(max_length=5, default=0) 
    status = models.CharField(max_length=15, choices=STATUS_CHOICES, default='no') 

    def __unicode__(self): 
     return str(self.player) 

現在,這裏是我的admin.py包括formfield_for_foreignkey,但它不工作。

class BattingInline(admin.TabularInline): 
    model = BattingDetail 
    extra = 0 

    def formfield_for_foreignkey(self, db_field, request=None, **kwargs): 

     if db_field.name == 'player': 
      kwargs = Player.objects.filter(team = request.team) 
     else: 
      pass 

     return super(BattingInline, self).formfield_for_foreignkey(db_field, request, **kwargs) 


class InningCardAdmin(admin.ModelAdmin): 
    inlines = [BattingInline] 

哪裏可能會出錯?

//鼠標

回答

7
  1. 你與查詢集替換整個kwargskwargs必須是一本字典,你要尋找的特定的鍵「查詢集」:

    kwargs['queryset'] = Player.objects.filter(team=request.team) 
    
  2. 我幾乎可以肯定要求不會實際上有一個屬性team。除非你自己添加了一些代碼,而不是在這裏顯示,否則你需要找到另一種方式來獲得當前的「團隊」。例如,您可以從request.path解析出團隊ID,並將其用於查找。

作爲一個側面說明,else條款是不必要的,如果你只是去那裏pass