from django.db.models import CharField
try:
import uuid
except ImportError:
from django.utils import uuid
class UUIDField(CharField) :
def __init__(self, *args, **kwargs):
kwargs['max_length'] = kwargs.get('max_length', 32 )
CharField.__init__(self, *args, **kwargs)
def pre_save(self, model_instance, add):
if add :
value=getattr(model_instance,self.attname)
if not value:
value = unicode(uuid.uuid4()).replace('-','')
setattr(model_instance, self.attname, value)
return value
else:
return super(CharField, self).pre_save(model_instance, add)
Comments
Instead of: value = unicode(uuid.uuid4()).replace('-','')
It would be better: value = unicode(uuid.uuid4().hex)
Also, check this: http://code.google.com/p/django-command-extensions
They have something like this (is this better?)
#