问题
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