I’d like to override a model’s save method to set an attribute to a value equal to the max of that column and have it all done as one statement to avoid race conditions. Effectively I want to do a:
INSERT INTO mytable (id, number, anotherthing) values (‘1234’, (select max(number) + 1 where anotherthing=‘abcd’), ‘abcd’)
Is there any way to do this with Django Model syntax without using RawSQL?
My gut reaction to this is that this isn’t necessarily resistant to a race condition even if you were to do it using raw SQL.
The database-independent way of handling this is through using an autoincrement field, which in PostgreSQL is done with the aid of a sequence object.
So if I were looking at this, my definition for number
would be:
number = models.AutoField()
If for some reason this isn’t an appropriate solution for you, then I believe you would need to do this using raw SQL - and doing a full table lock while executing your query / insert.