| published by | Software Crafts |
|---|---|
| in blog | Software Crafts |
| original entry | How not to create primary keys in Django |
I have have said this before, but I was reminded of it yesterday, just use the defaults provided by Django for primary keys. There is the unique kwarg on any field if you need another identifier.
Here are some examples I have seen in the wild of other primary key generated (all of which have generated issues at some point)
def gen_id_small():
t = int(time.time()) - 1615005089
u = random.SystemRandom().getrandbits(4)
return (t << 4) | u
def gen_id_large():
t = int(time.time()) - settings.BASE_TIME
u = random.SystemRandom().getrandbits(16)
return (t << 16) | u
The above functions are set as callables on the id field, this leads to clashes if too many objects are created at same time, additionally it does computation in python and not in the DB which is always going to be problematic.
Also this one from an old job doesn't suffer from clashes, but makes it hard to use with other libraries that assume a numeric primary key. I definitely hit this once or twice when trying to do something on this codebase.
from shortuuidfield import ShortUUIDField
class Model(models.Model)
id = ShortUUIDField(auto=True, primary_key=True)
Do you have any code scars that should be avoided in future?