Search code examples
databasedjango-modelsormprimary-keydjango-orm

When should override and use custom primary key django?


Inheriting django Model causes a model to have a default primary key (id),

by default django generates BigAutoField for primary keys.

I have Checked some of the famous apps written in django like posthog, zulip, sentry, mozilla addons-server and all of them have used custom primary key.

(some of them have used both custom primary key and default)

I'm wondering when should we override this behavior and have custom primary key?

to clarify: obviously, my question is not when should change the primary key to something else (e.g. to name or email field), cause that depends on your desicion actually.

I wanna know what is drawback of the default primary key and should I be worried about it?


Solution

  • One drawback is that the default autofield increments by 1 each time, so your first model instance will have an id of 1 then 2 then 3 etc. Let's say that you can access user public profiles by domain.com/<userid>/profile. This is a security risk because it's trivial to find out the database ID of any given user, the number of users etc, and this holds true for any model that uses that pattern.