Skip to content
Advertisement

How can auto create uuid column with django

I’m using django to create database tables for mysql,and I want it can create a column which type is uuid,I hope it can generate the uuid by itself,that means each time insert a record,I needn’t specify a uuid for the model object.How can I make it,thanks!

Advertisement

Answer

If you’re using Django >= 1.8, you can use a UUIDField:

import uuid
from django.db import models

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

Passing default = uuid.uuid4 auto-populates new records with a random UUID (but note that this will be done in Python code, not at the database level).


If you’re using an older version of Django, you can either upgrade, or use django-extensions, which provides a UUIDField as well.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement