Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can auto create uuid column with django

Tags:

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!

like image 967
starkshang Avatar asked Dec 14 '15 10:12

starkshang


People also ask

What is the use of UUID field in Django?

UUIDField is a special field to store universally unique identifiers. It uses Python's UUID class. UUID, Universal Unique Identifier, is a python library that helps in generating random objects of 128 bits as ids.


1 Answers

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.

like image 67
Thomas Orozco Avatar answered Oct 11 '22 11:10

Thomas Orozco