N
N
newvasyuki2021-02-18 13:17:54
Django
newvasyuki, 2021-02-18 13:17:54

Why is m2m not saved?

There are two models and signal

class Hobby(models.Model):
    name = models.CharField(max_length=255)

class User(models.Model):
    main_hobby = models.ForeignKey(Hobby, null=True, blank=True, on_delete=models.SET_NULL)
    hobbies = models.ManyToManyField(Hobby, blank=True)

@receiver(pre_save, sender=User):
def update_hobbies(sender,  instance, **kwargs):
     if instance.main_hobby:
          instance.hobbies.add(instance.main_hobby)


As a result, the hobbies field is not updated. I also tried post_save - the picture is the same. The signal itself works, but nothing is saved. CHADNT?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Kuzmichev, 2021-02-19
@Assargin

So, you save from the admin panel, which means that your signal ( post_savenecessarily, it pre_save’s definitely past here) works out immediately after the object is saved User. So far everything is ok.
But it is with the admin panel that there is a nuance: after the main model is saved and the signals corresponding to this action are executed, the m2m connections that you have 100% on the admin page will start saving, and will overwrite the data that you saved milliseconds earlier using the signal.
I once had a similar problem, and if my memory serves me, I created my own signal, which I called from the overridden method of the model admin class after saving everything in general, and in the handler of my custom signal I already quietly worked with m2m-connections without these problems .
Also, you can play around with Django's signal m2m_changed, but it will be a hack, because this signal will be called 2N times, where N is the number of additions / deletions from m2m.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question