大概就是在Override save方法的时候, admin是不能直接更新ManytoManyField的, 虽然在save后可以看到M2M改变了,但其实后来会被admin改回去(当时debug到这里简直要抓狂了(╯‵□′)╯︵┻━┻)。
admin会在save后clean掉M2M的数据,然后添加上它知道数据(大概就是表单数据)。
所以我们要override它的clean方法,或者一堆monkey patch…Orz
大概就是这样override
class UserGroupAdminForm(ModelForm):
class Meta:
model = UserGroup
def clean(self):
"""Make sure all managers are also members. example"""
for manager in self.cleaned_data['managers']:
if manager not in self.cleaned_data['members']:
self.cleaned_data['members'].append(manager)
return self.cleaned_data
class UserGroupAdmin(admin.ModelAdmin):
model = UserGroup
form = UserGroupAdminForm