大概就是在Override save方法的時候, admin是不能直接更新ManytoManyField的, 雖然在save後能夠看到M2M改變了,但其實後來會被admin改回去(當時debug到這裏簡直要抓狂了(╯‵□′)╯︵┻━┻)。
admin會在save後clean掉M2M的數據,而後添加上它知道數據(大概就是表單數據)。
因此咱們要override它的clean方法,或者一堆monkey patch...Orz
大概就是這樣overridehtml
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
解決方法來源web