ManyToManyField aren't available in the post_save signal

狂风中的少年 提交于 2019-12-24 16:41:13

问题


I need to manipulate data from a Django model after its saving, but I also need to access the ManyToManyField.

Here's what I want to do:

class Lab(Model):
  institute = ManyToManyField(Institute)

def post_save_lab(sender, instance, created, *args, **kwargs):
  if not instance.institute.all():
    # Data processing...

post_save.connect(post_save_lab, sender=Lab)

The problem is, instance.institute.all() is always empty at that moment... How can I know if the lab has or has not institute?

I specify that the signal m2m_changed doesn't solve the problem because my data processing must be done if there are NO elements in the ManyToMany relation. Therefor m2m_changed will not be called.

Thanks!


回答1:


The m2m cannot be saved until model instance is saved. If you are looking for m2m instances when object is created created==True in post save signal then it will be always empty.

I think you can have handler for m2m_changed signal.




回答2:


You can override the save method:

class Lab(Model):
    institute = ManyToManyField(Institute)

    def save(self, *args, **kwargs):
        super(Lab, self).save(*args, **kwargs)
        # ... do something with the many to many
        # example:
        # if self.institute.all().exists():
        #     ...


来源:https://stackoverflow.com/questions/16539686/manytomanyfield-arent-available-in-the-post-save-signal

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!