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. UUIDField by bwhittington 4 years ago
  2. staticview for app by limodou 5 years, 11 months ago
  3. create_model_instances management command by Lacrymology 4 months ago
  4. New Pattern by Oduvan 4 years, 6 months ago
  5. Save disk space by hard-linking multiple Django installations by akaihola 6 years, 1 month ago

Comments

rpwagner (on March 19, 2008):

FYI - This example is mostly correctly; when a new object is saved, a new UUID is saved to the database, but the corresponding model_instance's attribute is not updated.

This example seems to work correctly.

Here's a demo of the behavior using this snippet:

from django.db import models
from uuid_field import UUIDField

class Run(models.Model):
    uuid = UUIDField(primary_key=True)

In [2]: from run_tracker.models import Run

In [3]: r = Run()

In [4]: r.uuid
Out[4]: ''

In [5]: r.save()

In [6]: r.uuid
Out[6]: ''

In [7]: r = Run.objects.create()

In [8]: r.uuid
Out[8]: ''

#

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.

#

sid123 (on September 15, 2009):

See here for another version - http://www.davidcramer.net/code/420/improved-uuidfield-in-django.html

#

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?)