[Solved]-Django save previous object from models

5๐Ÿ‘

โœ…

M2M relationships arenโ€™t saved as part of the save() method.
In the admin, the main object is saved, and then the m2m relation is saved; so, by serializing the list of tags in the save method, youโ€™re printing the value of the tags before the new values have been saved.
If you want to install โ€œpost m2m saveโ€ behavior, youโ€™d need to override the update view on the admin itself.

๐Ÿ‘คChristian Frei

4๐Ÿ‘

You are trying to initialize the ManyToMany attribute (.Servers) when creating the object..

Wherever you try to create the SourceDestinationGroup, you should probably create it THEN do:

group.Servers = servers
group.save()

Or, remove the Servers attribute in the init method and reset it afterwards:

def __init__(self, *args, **kw):
    super(SourceDestinationGroup, self).__init__(*args, **kw)
    self._temp_Servers = self.Servers

def save(self, **kw):
    if self.id is None:
        self._temp_Servers = self.Servers
        self.Servers = None # Your 'Servers' attribute was still being set, hence raising an Exception in the super.save just after
    super(SourceDestinationGroup, self).save(**kw)
    if self._old_Servers is not None:
        self.Servers = self._temp_Servers 
        super(SourceDestinationGroup, self).save(**kw)
๐Ÿ‘คameunier

3๐Ÿ‘

I encountered this problem a few month ago. The m2m relationships are not updated inside the model save method, even if super() is called before using those relationships.

The only workaround Iโ€™ve found is to write a separate function that deals with m2m relationships, and call it from the save method of the form:

def save(self, *args, **kwargs):
    instance = super().save(*args, **kwargs)
    instance.update_m2m()
    return instance

In your case, this function is the nearly the same as your model save method:

def update_m2m(self):
    if self.Servers != self._old_Servers:
       self.Status = 'C'
       self._old_Servers = self.Servers
       self.save()
๐Ÿ‘คalbar

1๐Ÿ‘

Your SourceDestinationGroup instance must be saved to database before you can add any servers to it. You probably can do an easy fix to it in your save method:

def save(self, **kw):
    if self.id is not None and self.Servers != self._old_Servers:
        self.Status = 'C'
        self._old_Servers = self.Servers

    super(SourceDestinationGroup, self).save(**kw)

As I can see, your change of server only makes sense when there are any old values.

๐Ÿ‘คGwynBleidD

Leave a comment