Categories
Python Answers

How to use a UUID as a primary key in Python Django models?

Spread the love

To use a UUID as a primary key in Python Django models, we can create a UUIDField.

For instance, we write

import uuid
from django.db import models

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

to create the id UUIDField in MyUUIDModel.

And then we set the default value to the value returned by uuid.uuid4.

We set primary_key to True to make id the primary key column.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *