ManyToManyField is empty in post_save () function

When a new record is added to the table, I have to execute the SQL statement in the external database. This request includes the use of ManyToManyField. So I just hooked up the function as follows:

post_save.connect(post_save_mymodel, sender=MyModel) 

And in my post_save_mymodel () function, here is what I do:

 def post_save_mymodel(sender, instance, created, *args, **kwargs): if created: for e in instance.my_m2mfield.all(): # Query including "e". 

But too bad, instance.my_m2mfield.all () is always empty! Although they should contain some elements! I tried to get a new item by doing

 new_element = MyModel.objects.get(pk=instance.pk) 

but it doesn’t change anything, I still have the same problem ...

Helpful help / advice?

+6
source share
1 answer

This is because you first saved your instance and then added the m2m relationship to it. This is how many ToToMany fields work in Django data models. Django needs to know the identifier of the elements that should be associated with the m2m relationships.

I think your code is as follows:

 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 the handler to the django.db.models.signals.m2m_changed signal. See documents . For instance:

 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) 
+6
source

All Articles