我有3个模型Team,Player和Fixture。
夹具
class Fixture(models.Model):
"""(Fixture description)"""
home = models.ForeignKey(Team, related_name="home_games")
away = models.ForeignKey(Team, related_name="away_games")
home_players = models.ManyToManyField(Player, related_name="home_games")
away_players = models.ManyToManyField(Player, related_name="away_games")
class Player(models.Model):
"""(Player description)"""
surname = models.CharField(blank=True, max_length=255)
forename = models.CharField(blank=True, max_length=255)
number = models.IntegerField(blank=True, null=True)
team = models.ForeignKey(Team, related_name="players")
class Team(models.Model):
"""(Team description)"""
name = models.CharField(blank=True, max_length=255)
location = models.CharField(blank=True, max_length=255)
你可以看到一个球员属于一个球队。 Fixture作为home_team,away_team,home_players和away_players。现在,在管理员的指导下,“home_players”会列出所有球队的所有球员。
我对django管理应用程序不熟悉,但我如何才能显示属于home_team的home_players和属于away_teams的away_players?
由于
答案 0 :(得分:2)
要让您的away_players
字段自动更新,因为您选择了您需要使用JavasScript的主页或离队。
away_players
字段。 (查看get_urls此代码可能存在的位置)绝对不支持开箱即用。
通常要在m2m字段或外键上过滤结果,您可以使用formfield_for_manytomany
,但它无权访问正在编辑的对象,因此我认为通过此方法无法实现。< / p>
我认为最简单的解决方案是制作表格2阶段:
您还可以覆盖admin add
视图,以便仅显示前两个字段。
class MyForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
# make sure we're editing a saved model
if self.instance.id:
self.fields['home_players'].queryset = Player.objects.filter(team=self.instance.home)
self.fields['away_players'].queryset = Player.objects.filter(team=self.instance.away)
class Meta:
model = Fixture
class MyAdmin(admin.ModelAdmin):
form = MyForm