Reputation: 13761
In my Model I have a ManyToManyField
over a different Model:
class A(models.Model):
...
class B(models.Model):
field = models.ManyToManyField(A)
Assuming I have field
poblated with some values, I'm trying to get a list of the items that the user unselected before hitting the Save
button. For that, I've overloaded the save()
method inside B
:
def save(self, *args, **kwargs):
super(B, self).save(*args, **kwargs)
print self.field.all()
However, when hitting the Save
button, the values of self.field.all()
I get are the ones that I had when I loaded the form.
For example, if I had two selected items in the list (a
and b
) and I unselect b
and hit the Save
button, self.field.all()
at save()
time is still a
and b
. If I edit the item again, I see b
is unselected, I select it back and at save()
time self.field.all()
is only a
.
My assumption is that unselected items are processed after the save()
method, although I haven't found a reference in the Django documentation.
Is there a way to get the updated list at save()
time? If not, is there a method I can overload to handle the list update within the Model definition?
(Note: Alternatives are also welcome.)
Upvotes: 0
Views: 850
Reputation: 1659
There is a similar question regarding the m2m behavior :
Django: accessing ManyToManyField objects after the save
The reason you're not getting the updated data at the time save() is called is because Django handles the many to many relation changes later, and it can be accessed via the m2m_changed signal.
Hope this helps,
Regards
Upvotes: 1