Generate unique id in django from a model field

PythonDjangoDjango Models

Python Problem Overview


I want to generate different/unique id per request in django from models field. I did this but I keep getting the same id.

class Paid(models.Model):
     user=models.ForeignKey(User)
     eyw_transactionref=models.CharField(max_length=100, null=True, blank=True, unique=True, default=uuid.uuid4()) #want to generate new unique id from this field

     def __unicode__(self):
        return self.user

Python Solutions


Solution 1 - Python

Since version 1.8 Django has UUIDField

import uuid
from django.db import models

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

Solution 2 - Python

If you are using Django 1.8 or superior, madzohan's answer is the right answer.


Do it like this:

#note the uuid without parenthesis
eyw_transactionref=models.CharField(max_length=100, blank=True, unique=True, default=uuid.uuid4)

The reason why is because with the parenthesis you evaluate the function when the model is imported and this will yield an uuid which will be used for every instance created.

Without parenthesis you passed just the function needed to be called to give the default value to the field and it will be called each time the model is imported.

You can also take this approach:

class Paid(models.Model):
     user=models.ForeignKey(User)
     eyw_transactionref=models.CharField(max_length=100, null=True, blank=True, unique=True)

     def __init__(self):
         super(Paid, self).__init__()
         self.eyw_transactionref = str(uuid.uuid4())

     def __unicode__(self):
        return self.user

Solution 3 - Python

If you need or want to use a custom ID-generating function rather than Django's UUID field, you can use a while loop in the save() method. For sufficiently large unique IDs, this will almost never result in more than a single db call to verify uniqueness:

urlhash = models.CharField(max_length=6, null=True, blank=True, unique=True)

# Sample of an ID generator - could be any string/number generator
# For a 6-char field, this one yields 2.1 billion unique IDs
def id_generator(size=6, chars=string.ascii_uppercase + string.digits):
    return ''.join(random.choice(chars) for _ in range(size))

def save(self):
    if not self.urlhash:
        # Generate ID once, then check the db. If exists, keep trying.
        self.urlhash = id_generator()
        while MyModel.objects.filter(urlhash=self.urlhash).exists():
            self.urlhash = id_generator()
    super(MyModel, self).save()

Solution 4 - Python

This answer from Google Code worked for me:

https://groups.google.com/d/msg/south-users/dTyajWop-ZM/-AeuLaGKtyEJ

add:

from uuid import UUID

to your generated migration file.

Solution 5 - Python

you can use uuid for this task. UUIDField is a special field to store universally unique identifiers. Universally unique identifiers are a good alternative to AutoField for primary_key. The database will not generate the UUID for you, so it is recommended to use default.

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

for more detail visit this link

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionpicomonView Question on Stackoverflow
Solution 1 - PythonmadzohanView Answer on Stackoverflow
Solution 2 - PythonPaulo BuView Answer on Stackoverflow
Solution 3 - PythonshackerView Answer on Stackoverflow
Solution 4 - PythonwoodardjView Answer on Stackoverflow
Solution 5 - PythonAlphonse PrakashView Answer on Stackoverflow