How to use UUID as primary key in a Django Model?

How to use UUID as primary key in a Django Model?

How to use a UUID field instead of the default ID field as primary key in Django?

If you are creating a model in Django, Django automatically defines a primary key field called id in the database for that model. But in some cases, you might want to specify your own id field as primary key. It is easy peasy to do in Django, let’s have a look at it.

from uuid import uuid4
from django.db import models

class Book(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid4, editable=False)

In the above example, we are using a UUIDField as our primary key field i.e. id , also it is to notice that we are providing a default value to the UUIDField as uuid4 which is imported from the uuid module.

If you want a field to be primary key in Django, you have to specify the primary_key=True as an argument in that field. Keep in mind that Django does not allow to have more than one primary keys, although it allows you to specify unique fields.

Any thoughts? Write it down in the comments.

For more such crispy blogs daily, follow Dev.Junction, subscribe to our newsletter and get notified.