picomon picomon - 6 months ago 242
Python Question

Generate unique id in django from a model field

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

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

Hope this helps!