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!
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With