I think the best way to get closer to your desired behavior is not signals, but rather an overridden save () and delete () method in the through table, which you would explicitly define using the through argument, see https: //docs.djangoproject. com / en / dev / ref / models / fields / # django.db.models.ManyToManyField.through . and this: https://docs.djangoproject.com/en/dev/topics/db/models/#overriding-predefined-model-methods
Something like that:
# -*- coding: utf-8 -*- from django.db import models class Item(models.Model):
By the way, you will find that adding a relation will cause a save signal on this model.
And, with regard to signals, as soon as you have an end-to-end table, you can listen to the signals pre_save and / or post_save, but none of them will allow you to directly veto the creation of the relationship.
If one or both models are supplied by a third party, and you really cannot create an end-to-end table, then yes, the signal path may be the only way.
https://docs.djangoproject.com/en/dev/ref/signals/#m2m-changed
In this case, you can listen to the m2m_changed event and trigger updates for your collection objects (part 2 of your question) and retroactively delete improper relationships created (part 1 of your question). However, since this last bit is ugly kludgy, I would stick to an explicit table if you can.
source share