Login

UUIDField

Author:
trbs
Posted:
July 22, 2007
Language:
Python
Version:
.96
Score:
4 (after 4 ratings)

UUIDField is a field which stores an uuid generated by pythons new uuid module.

it's included with the python 2.5 distribution by default, but if you run an older version of python you can happily copy the file from 2.5 to django/utils/uuid.py or your project directory.

 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. Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 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.

#

Please login first before commenting.