如何在Django中使用UUID [英] how to use UUID in Django

查看:1019
本文介绍了如何在Django中使用UUID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为Django对象获取唯一的ID。在Django 1.8中,它们具有UUIDField。我不确定如何使用此字段来为模型中的每个对象生成唯一的ID。

I am trying to get unique IDs for my Django objects. In Django 1.8 they have the UUIDField. I am unsure how to use this field in order to generate unique IDs for each object in my model.

这里是UUIDField的内容

Here is what I have for the UUIDField

import uuid
from django.db import models

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

class Person(models.Model):
    ...
    unique_id = MyUUIDModel()

我可以重现UUID模型的ID,但是每次我得到的都完全相同ID。 :(。例如:

I can reproduce the id for the UUID model, but everytime I do I get the exact same id. :(. For Example:

person = Person.objects.get(some_field = some_thing)
id = person.unique_id.id

id然后每次都给我相同的ID。怎么了,怎么解决

id then gives me the same id every time. What is wrong, how do I fix this? Thank you for your help!

推荐答案

我不确定为什么创建了UUID模型。您可以添加

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)

每个人都应该拥有一个唯一ID如果要让uuid作为主键,则可以执行以下操作:

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)

您当前的代码尚未向人员添加字段,它在您执行MyUUIDModel()时创建了 MyUUIDModel 实例,将其作为类属性。这样做没有任何意义,每次加载models.py时都会创建 MyUUIDModel 。如果您确实想使用MyUUIDModel,则可以使用 ForeignKey 。然后每个人都将链接到不同的MyUUIDModel实例。

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)

但是,我说过以前,最简单的方法是将UUID字段直接添加到人员。

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

这篇关于如何在Django中使用UUID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆