I have a model called Goal and another one called Action. Here I highlight the important parts:
class Goal(models.Model):
leaders = models.ManyToManyField(User, null=True)
class Action(models.Model):
before = models.TextField(null=True)
after = models.TextField(null=True)
When a user edits a Goal I save a new Action object. One of this Action object’s property is before and after. before and after are serialized Goal objects. They will be used later to record what was changed in the Goal object.
All properties work fine(like title and description), the problem is with a ManyToMany field called ‘leaders’, when i deserialize the goal object with:
before = action.before
for obj in serializers.deserialize("xml", before):
before_object = obj
after = action.after
for obj in serializers.deserialize("xml", after):
after_object = obj
and try to access the leaders field with:
before_object_leaders = before_object.object.leaders.all()
after_object_leaders = after_object.object.leaders.all()
leaders_updated = True
if set(before_object_leaders) == set(after_object_leaders):
leaders_updated = False
before_object_leaders gets the current value in the Goal table for the Goal object, and not the value in the deserialized object, which is what I want. (the old value, before the update)
Please help, I’m going insane. Thanks!
The issue here is, as soon as you call:
before_object.object.leadersyou are getting a ModelManager which will make new DB queries when you call the methodall()! thats the default behaviour of the ModelManager.So, to solve your problem you will have to write a new manager within your Model object. and this Manager will be responsible for the deserialize of leaders.
here is some reference:
https://docs.djangoproject.com/en/dev/topics/db/managers/