[Answered ]-Django Python unique=True Expression

0πŸ‘

βœ…

None of this has anything to do with Django at all. This is pure database stuff: unique constraints are handled exclusively by the database, in your case SQLite, although the functionality is exactly the same for other DBs as well.

Of course, a unique constraint only takes into account rows that actually exist: what would be the point otherwise?

There are other things to bear in mind with your proposal as well. In particular, there is the issue of race conditions: if you do a query to get the maximum key value, and then create a new row with key+1, you run the risk of another user in the meantime adding their own row at key+1. Much better, as Iris and ryanageles suggest, to use the built-in primary key which is already automatically defined as the id field.

2πŸ‘

Seems like you are looking for something that already exists; models have an id field by default which is unique and monotonic (newer entries have bigger id).

πŸ‘€Iris

0πŸ‘

try to add primary_key=True in your key field.

πŸ‘€rynangeles

Leave a comment