Home > Enterprise >  How to avoid double saving after defining the `Save` method on the Model?
How to avoid double saving after defining the `Save` method on the Model?

Time:10-03

I have defined a Save method in my model for the order fields.

Now, when I do some manipulations with the Order field in View and call save() - I save twice - in View save() and Model save().

Because of this, the problem! How to solve this problem? How to make Save work only when creating a model object? And don't work save when I save() in Views

save

def save(self, *args, **kwargs):
    model_class = type(self)
    last_item = model_class.objects.order_by('-order').first()
    if last_item is not None:
        self.order = last_item.order  = 1

    super().save(*args, **kwargs)

CodePudding user response:

If I understand correctly, then you want the extra code in the save method to only run on creation, not when updating the model instance.

Before the object is created in the database, its PK is None. You could use that to check if it is a creation or update operation.

def save(self, *args, **kwargs):
    if self.pk is None:
        # this code will only be executed when the object is created
        model_class = type(self)
        last_item = model_class.objects.order_by('-order').first()
        if last_item is not None:
            self.order = last_item.order   1
        else:
            self.order = 0

    super().save(*args, **kwargs)
  • Related