formfield_for_foreignkey和Inline Admin [英] formfield_for_foreignkey and Inline Admin
问题描述
我只想在特定的灯具中显示与团队相关的玩家。通常当我这样做,它显示了我所有的玩家从数据库。这是我的models.py
I only want to show the players related to team in a particular fixture. Normally when I do it, it shows me all my players from the database. Here is my 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,但不起作用。
Now and here is my admin.py to include formfield_for_foreignkey, but it doesn't work.
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]
我可以在哪里出现错误?
where could i be going wrong?
//鼠标
推荐答案
-
您正在使用查询器替换整个
kwargs
。kwargs
必须是字典,您要查找的特定键是'queryset':
You're replacing the entire
kwargs
with the queryset.kwargs
must be a dictionary, and the particular key you're looking for is 'queryset':
kwargs['queryset'] = Player.objects.filter(team=request.team)
我几乎是积极的请求,实际上不会有一个属性 team
。除非你自己添加了一些不显示在这里的代码,否则你需要找到另一种方式来获取当前的团队。您可以从 request.path
中解析出团队ID,并将其用于查找。例如
I'm almost positive request isn't going to actually have an attribute team
. Unless you've added it yourself in some code not displayed here, you need to find another way to get at the current "team". You can parse out the team id from request.path
and use that for the lookup, for example.
作为一个附注,如果你要去 pass c c $ c> code>那里。
As a side note, the else
clause is unnecessary if you're just going to pass
there.
这篇关于formfield_for_foreignkey和Inline Admin的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!