UUIDField

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
from django.db.models import CharField

try:
    import uuid
except ImportError:
    from django.utils import uuid

class UUIDVersionError(Exception):
    pass

class UUIDField(CharField):
    """ UUIDField for Django, supports all uuid versions which are natively
        suported by the uuid python module.
    """

    def __init__(self, verbose_name=None, name=None, auto=True, version=1, node=None, clock_seq=None, namespace=None, **kwargs):
        kwargs['maxlength'] = 36
        if auto:
            kwargs['blank'] = True
            kwargs['editable'] = kwargs.get('editable', False)
        self.version = version
        if version==1:
            self.node, self.clock_seq = node, clock_seq
        elif version==3 or version==5:
            self.namespace, self.name = namespace, name
        CharField.__init__(self, verbose_name, name, **kwargs)

    def get_internal_type(self):
        return CharField.__name__

    def create_uuid(self):
        if not self.version or self.version==4:
            return uuid.uuid4()
        elif self.version==1:
            return uuid.uuid1(self.node, self.clock_seq)
        elif self.version==2:
            raise UUIDVersionError("UUID version 2 is not supported.")
        elif self.version==3:
            return uuid.uuid3(self.namespace, self.name)
        elif self.version==5:
            return uuid.uuid5(self.namespace, self.name)
        else:
            raise UUIDVersionError("UUID version %s is not valid." % self.version)

    def pre_save(self, model_instance, add):
        if self.auto and add:
            value = unicode(self.create_uuid())
            setattr(model_instance, self.attname, value)
            return value
        else:
            value = super(UUIDField, self).pre_save(model_instance, add)
            if self.auto and not value:
                value = unicode(self.create_uuid())
                setattr(model_instance, self.attname, value)
        return value

More like this

  1. autogenerated UUID model field by kedar 1 month, 2 weeks ago
  2. UUIDField by bwhittington 4 years, 11 months ago
  3. uuid template tag by nomadjourney 5 years, 1 month ago
  4. uuid model field by newspire 5 years, 3 months ago
  5. UUIDField oriented django User by bwhittington 4 years, 11 months ago

Comments

trbs (on March 28, 2008):

thanks rpwagner

i've updated the snipplet

#

sid123 (on September 15, 2009):

kwargs['maxlength'] = 36

shouldn't it be max_length, otherwise it gives an unexpected argument error.

#

guettli (on December 12, 2012):

New django ticket: https://code.djangoproject.com/ticket/19463

Jacob will consider a UUID field for core.

#

(Forgotten your password?)