我有Team
模型whit players
ManyToManyField,我希望能够在创建时将Player
添加到新团队,但在创建后无法修改它。
如果我将players
字段设为只读:
# admin.py
class TeamAdmin(admin.ModelAdmin)
readonly_fields = ['players']
admin.site.register(Team, TeamAdmin)
我无法将玩家添加到新Team
。
如何使players
字段“在创建之后只读”或类似的东西?
答案 0 :(得分:41)
您需要覆盖管理类的get_readonly_fields()
方法。
# admin.py
class TeamAdmin(admin.ModelAdmin)
...
def get_readonly_fields(self, request, obj=None):
if obj: #This is the case when obj is already created i.e. it's an edit
return ['players']
else:
return []