我遇到了一个问题,试图在admin:
中的model_save之后获取m2m字段值class MyModel(models.Model):
relation = models.ManyToManyField(MyRelatedModel, blank=False, null=False)
...
class MyModelAdmin(admin.ModelAdmin):
...
def save_model(self, request, obj, form, change):
super(MyModelAdmin, self).save_model(request, obj, form, change)
for rel in obj.relation.all():
# Code here is not executed on first (initial) save - why?
...
上面的代码适用于实例的第二次和后续保存,但不适用于初始保存。它不应该工作,因为我已经在MyModelAdmin.save_model上调用了super,或者是否有其他我缺少的东西并且m2m以某种方式单独保存?
答案 0 :(得分:2)
super
方法调用form.save_m2m()
之后:
class MyModelAdmin(admin.ModelAdmin):
...
def save_model(self, request, obj, form, change):
super(MyModelAdmin, self).save_model(request, obj, form, change)
form.save_m2m()