Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 
like image 982
picomon Avatar asked Jun 04 '13 18:06

picomon


People also ask

How do you generate unique random numbers in Django?

randint() method is used to generate a random number between the start and stop.

How do you generate unique identifiers?

The simplest way to generate identifiers is by a serial number. A steadily increasing number that is assigned to whatever you need to identify next. This is the approached used in most internal databases as well as some commonly encountered public identifiers.

What is __ Str__ in Django model?

The __str__() method is called whenever you call str() on an object. Django uses str(obj) in a number of places. Most notably, to display an object in the Django admin site and as the value inserted into a template when it displays an object.

Does Django model have ID?

By default, Django adds an id field to each model, which is used as the primary key for that model. You can create your own primary key field by adding the keyword arg primary_key=True to a field.


1 Answers

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 
like image 115
madzohan Avatar answered Sep 19 '22 15:09

madzohan