I'd like to use the user updated values of a ManyToManyField in a model's overriden save() method when I save an instance in admin.
It turns out that by design, django does开发者_C百科 not update the M2M field before calling save(), but only after the save() is complete as part of the form save...
e.g. in both print commands bellow the values displayed are that of before the user updated the model instance in admin:
class MyClass(models.Model):
an_m2m_field = models.ManyToManyField(MyOtherCLass)
def save(self, *args, **kwargs):
print self.an_m2m_field.all()
super(MyClass, self).save(*args, **kwargs) # Call the "real" save() method.
print self.an_m2m_field.all()
How can I access the new values of this field in the override save() ?
M2M fields are saved independently from the model. To act upon M2M field changes, register to the m2m_changed signal of the M2M field, as detailed here.
精彩评论