When a new record is added to a table, I have to execute a SQL statement on an external database. This query includes the use of a ManyToManyField. So I just connected the funct
This is because you first save your instance and after that you add m2m relations to it. This is how ManyToMany fields work in Django data models. Django needs to know the ID of the items that should be connected with m2m relations.
I think that your code looks like this:
instance = MyModel.objects.create(some_field=some_value) # post save signal triggered here
instance.my_m2mfield = my_set_of_m2m_models
You need to connect your handler to the django.db.models.signals.m2m_changed
signal. See the docs. For example:
def post_save_mymodel(sender, instance, action, reverse, *args, **kwargs):
if action == 'post_add' and not reverse:
for e in instance.my_m2mfield.all():
# Query including "e"
m2m_changed.connect(post_save_mymodel, sender=MyModel.my_m2mfield.through)