how to use UUID in Django

拜拜、爱过 提交于 2019-11-29 20:54:16

I'm not sure why you've created a UUID model. You can add the uuid field directly to the Person model.

class Person(models.Model):
    unique_id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True)

Each person should then have a unique id. If you wanted the uuid to be the primary key, you would do:

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

Your current code hasn't added a field to the person. It has created a MyUUIDModel instance when you do MyUUIDModel(), and saved it as a class attribute. It doesn't make sense to do that, the MyUUIDModel will be created each time the models.py loads. If you really wanted to use the MyUUIDModel, you could use a ForeignKey. Then each person would link to a different MyUUIDModel instance.

class Person(models.Model):
    ...
    unique_id = models.ForeignKey(MyUUIDModel, unique=True)

However, as I said earlier, the easiest approach is to add the UUID field directly to the person.

You need to use the class you created as a subclass when declaring your Person model like this:

import uuid
from django.db import models

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

class Person(MyUUIDModel):
  ...

This way Person becomes a subclass of MyUUIDModel and will inherit its id field definition.

You can directly add the id field as a UUIDField in the Person model. There is no need for a separate MyUUIDModel.

I think you have confused it with the MyUUIDModel used in the UUIDField example where the id is a UUIDField. You can just use the below code and it will use UUIDs for id.

import uuid
from django.db import models

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

To use UUID in Django for a new model see Django Docs.

However, if you want to use it for the existing model (with unique=True) having data corresponding to it, you will not be able to do it directly by the above documentation. It will create migration errors. To do it without losing the data follow all the steps carefully of this Django Documentation.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!