I have a Django model with 2 many-to-many fields. When the model is saved from the admin interface I need to check if the second field is blank and if it is blank then I need the items from the first fielded copied to the second. How can I do this?
UPDATE
Matthew’s answer seems like it would work great but I can’t get the instance to save after I copied the field. I have tried instance.save() without any success.
The signal to be use is not
post_save, ratherm2m_changed, that is sent much after the model is saved to the database.Edit: next code is simpler, and based upon new knowledge on the models definition
In your code the ‘first_m2m’ signals are sent before the the ‘second_m2m’ (it really depends on your model definition). So we can work on the assumption that when the ‘second_m2m’ signals are received, the ‘first_m2m’ is already populated with current data.
This makes us happier, because now you only need to check the m2m-pre-add: