django – formfield_for_foreignkey和内联管理员

前端之家收集整理的这篇文章主要介绍了django – formfield_for_foreignkey和内联管理员前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我只想在特定的比赛中展示与球队相关的球员.通常当我这样做时,它会向我显示数据库中的所有玩家.这是我的models.py
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]

哪里可能出错?

//老鼠

解决方法

>您将使用查询集替换整个kwargs. kwargs必须是字典,你要找的特定键是’queryset’:
kwargs['queryset'] = Player.objects.filter(team=request.team)

>我几乎是积极的请求,实际上并没有属性团队.除非你自己在这里没有显示代码添加它,否则你需要找到另一种方法来获得当前的“团队”.例如,您可以从request.path中解析出团队ID,并将其用于查找.

作为旁注,如果您要通过那里,则不需要else子句.

猜你在找的Python相关文章