Implementing UUID for Model User in Django & PostgreSQL

Gerry Sabar
2 min readAug 6, 2019
Photo by Markus Spiske on Unsplash

The default id structure for Django model is using auto-increment integer. For example when we create a user for the first time the id will be 1, when we create another user the id will be 2 and so on. If we’re implementing RESTful API to our Django project this will be a serious problem in security because anyone can make a guess for each user for example let’s say to get the first user the url is as follow:

/api/v1/users/1

Now, let’s try to implement uuid for model User which is a bit tricky than another model because model User is already made by default for Django. Let’s create a directory named uuid-project and create a virtual environment then activate your django virtual environment. Next, let’s install django using pip command

$ pip install django

Then we can create an app named user_uuid inside uuid-project directory using this command:

$ django-admin startproject user_uuid .

Then create an app inside django, let’s say test_uuid for now:

$ django-admin startapp user

Makesure our file structure is like this for now:

Now, to implement uuid to model user we need to alter default user which is provided by django. Let’s modify user/models.py as follow:

in settings.py we need to alter the authentication from default django user model to our adjusted model CustomUser, add this line in settings.py:

AUTH_USER_MODEL = 'user.CustomUser' 

Then re-run again migrate command:

python manage.py migrate

Now we have CustomUser model as a replacement from default user model from Django.

Why don’t we just alter the id from auto-increment to uuid?

Maybe some of you wondering why do we have id & uuid columns inside the table instead of replacing auto-increment id become uuid. The reason is querying record using uuid is slower than auto-increment id. If you’re working with small records this won’t be any issue, however as soon as your database getting bigger this will be an issue. You can see a good discussion here: https://dba.stackexchange.com/questions/115766/should-i-use-uuid-as-well-as-id . Therefore the solution is we keep auto-increment id and use it whenever possible. Anyone who access RESTful API can use uuid as the replacement for id from each record.

--

--