Django - Deserialize an object conserving ManyToMany field

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.leaders you are getting a ModelManager which will make new DB queries when you call the method all() ! 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:

Need Your Help

Check for matchings in R

r matching

I have a table with two columns:

Getting invalid datatype error while parsing xml in Oracle

plsql oracle11g

I am trying to parse XML in PL SQL. But getting following error