Search code examples
pythondjangodjango-modelsuuid

How to use UUID


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.

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()

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 then gives me the same id every time. What is wrong, how do I fix this?


Solution

  • 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.