In the Django Admin Site, how can I access model properties through an Inline?
models.py:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | class Player(models.Model): name = models.CharField(max_length=50) email = models.EmailField(max_length=50) class Tournament(models.Model): name = models.CharField(max_length=50) class TournamentPlayer(models.Model): tournament = models.ForeignKey(Tournament) player = models.ForeignKey(Player) paid = models.BooleanField() def player_email(self): return self.player.email |
admin.py:
1 2 3 4 5 6 7 | class TournamentPlayerInline(admin.TabularInline): model = TournamentPlayer fields = ('player', 'paid', 'player_email') @admin.register(Tournament) class TournamentAdmin(admin.ModelAdmin): inlines = [TournamentPlayerInline] |
在有一个内嵌的问题。我拉了锦标赛的网站管理员,可以看到哪些播放器是持续的,如果他们支付。我也喜欢显示额外的信息包含在播放器,例如电子邮件地址。
在tournamentplayerinline如果能够代表可能会离开,但我
在
如果从两个移动
这是是我在:
如何在Access播放器可以从tournamentplayerinline置业?
1.8.4 Django
猴子的回答几乎是正确的。你唯一需要做的改变是你的管理层,它只是在
1 2 3 4 5 6 7 8 | class TournamentPlayerInline(admin.TabularInline): model = TournamentPlayer fields = ('player', 'player_email', 'paid',) readonly_fields = ('player_email',) @admin.register(Tournament) class TournamentAdmin(admin.ModelAdmin): inlines = [TournamentPlayerInline] |
号
如果不要求从内联编辑
1 2 3 4 5 6 7 8 | class TournamentPlayerInline(admin.TabularInline): model = TournamentPlayer fields = ('player', 'paid') readonly_fields = ('player_email',) @admin.register(Tournament) class TournamentAdmin(admin.ModelAdmin): inlines = [TournamentPlayerInline] |
另一种选择是,如果不直接使用自定义属性,您不必在模型中定义它,只需在管理中查看它——您可以通过mixin在内联中创建它:
型号.py
1 2 3 4 5 6 7 8 9 10 11 | class Player(models.Model): name = models.CharField(max_length=50) email = models.EmailField(max_length=50) class Tournament(models.Model): name = models.CharField(max_length=50) class TournamentPlayer(models.Model): tournament = models.ForeignKey(Tournament) player = models.ForeignKey(Player) paid = models.BooleanField() |
行政副总裁
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | class PlayerEmailMixin(object): def player_email(self, obj): return obj.player.email player_email.short_description ="Player Email" class TournamentPlayerInline(PlayerEmailMixin, admin.TabularInline): model = TournamentPlayer fields = ('player', 'player_email', 'paid', ) readonly_fields = ('player_email',) @admin.register(Tournament) class TournamentAdmin(admin.ModelAdmin): inlines = [TournamentPlayerInline] |
。
您也可以通过以下方式将其设置为mailto-uri:
1 2 3 4 5 6 | class PlayerEmailMixin(object): def player_email(self, obj): return '{0}'.format(obj.player.email) player_email.short_description ="Player Email" player_email.allow_tags = True |
这在Django 1.9.5是已知的。