Django:在model_save之后得到m2m值

时间:2014-04-11 13:54:43

标签: django django-admin

我遇到了一个问题,试图在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以某种方式单独保存?

1 个答案:

答案 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()