Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django UUIDField with Postgresql

Is there an advantage for using UUIDField with Django and Postgresql (native datatype) over a self-made generated unique key?

Currently I use a random-generated alphanumeric ID field on my models and I am wondering if the Postgres native datatype and the UUIDField are better for this purpose and whether there's a reason to switch over.

I generate the id using random letters and digits. It's 25 chars long. I put a db_index on it for faster retrieval. I don't shard my DB. The reason being that some models cannot have consecutive ids for business purposes

like image 873
elynch Avatar asked Sep 02 '26 12:09

elynch


1 Answers

Switching to UUID will have an advantage particularly if you have a large number of records. Lookups and inserts ought to be a tiny bit faster. You will be saving 9 bytes of storage per row since UUID fields are only 128 bits.

However that doesn't mean your home made primary key is a bad idea. Far from it. It's a good one and a similar approach is used by Instagram who also happen to be using Postgresq and DJango. Their solution though uses only 64 bits and also manages to squeeze in information about object creation time into the primary key.

Their primary purpose is sharding but works very well even for non shared dbs. Just use some random number for the 13 bits that represent their sharding information. They have a sql sample at the link above.

like image 111
e4c5 Avatar answered Sep 04 '26 09:09

e4c5



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!