1

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)
Elliot13
  • 368
  • 2
  • 4
  • 16
  • I don't understand. Could you add the code of your model `save()` method? – Ralf Oct 01 '21 at 17:28
  • @Ralf Yes, is your code – Elliot13 Oct 01 '21 at 17:34
  • This seems like an [XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). It seems you just want an autoincrementing primary key? Also your solution is prone to race conditions, it is highly likely that multiple instances may end up with the same value for `order`... See [How do I make an auto increment integer field in Django?](https://stackoverflow.com/questions/21128899/how-do-i-make-an-auto-increment-integer-field-in-django) – Abdul Aziz Barkat Oct 01 '21 at 17:44
  • if i will use auto increments `models.AutoField(primary_key=True)` - can i will change the values in `views`? – Elliot13 Oct 01 '21 at 18:28

1 Answers1

1

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)
Ralf
  • 16,086
  • 4
  • 44
  • 68
  • Other option: using [`Model._state`](https://docs.djangoproject.com/en/3.2/ref/models/instances/#django.db.models.Model._state) – Ralf Oct 01 '21 at 17:45
  • Related question: https://stackoverflow.com/questions/907695/in-a-django-model-custom-save-method-how-should-you-identify-a-new-object – Ralf Oct 01 '21 at 17:46