R
R
RabbitRun92021-10-01 20:13:14
Django
RabbitRun9, 2021-10-01 20:13:14

How to override the save method of the model only for new records?

Hello! Faced a very interesting situation, I just can not come up with an adequate working solution. Community help needed!

The situation is this: there is a Post model and the model has an Order field (in addition to other name fields, etc.), it is for arbitrary sorting, and so, I overridden the Save method of this Post model so that when creating a new record, +1 is assigned to the last existing index. An analogue of id, but I will swap these indices and sort the records as I need.

But I ran into a problem, now when I wrote a function in views that swaps indexes, when it calls save to save the result, it doubles the indexes, due to the fact that in the model we will already override the save method with +1 to the index.

I can't deal with the problem. There is an idea in the logic of overriding the Save method of the model to do some kind of check: if the record is new without an index in the Order field (empty), then only then we assign +1 from the last one already available for other records, if the index already exists, then not resave it again, and probably then just pass, something like this, for example, well, like, do nothing more! And how will this affect the save logic in views? After all, I'm trying to change and save existing indexes there.

Here is such a problem.
Can anyone come across a similar, what are the solutions, what ideas?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gornostaev, 2021-10-01
@RabbitRun9

First, it's bad practice to override save, it's better to use signals. Secondly, your solution cannot be stable in principle and will have terrible performance, declining exponentially as the number of orders increases. Finally, if you really want to do something bad, you can check the value of the pk field. For new entries, it will be None.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question