1 | from django.db import models
|
---|
2 |
|
---|
3 | class UUIDField(models.CharField):
|
---|
4 | def __init__(self, version=None, node=None, clock_seq=None, namespace=None, name=None, **kwargs):
|
---|
5 | kwargs['maxlength'] = 36
|
---|
6 | kwargs['blank'] = True
|
---|
7 | self.version = version
|
---|
8 | if version==1:
|
---|
9 | self.node, self.clock_seq = node, clock_seq
|
---|
10 | elif version==3 or version==5:
|
---|
11 | self.namespace, self.name = namespace, name
|
---|
12 | models.CharField.__init__(self, **kwargs)
|
---|
13 |
|
---|
14 | def get_internal_type(self):
|
---|
15 | return "CharField"
|
---|
16 |
|
---|
17 | def pre_save(self, model_instance, add):
|
---|
18 | if add:
|
---|
19 | import sys
|
---|
20 | if sys.version_info < (2,5):
|
---|
21 | try:
|
---|
22 | from django.utils import uuid
|
---|
23 | except ImportError:
|
---|
24 | import uuid
|
---|
25 | else:
|
---|
26 | import uuid
|
---|
27 | if not self.version or self.version==4:
|
---|
28 | return unicode(uuid.uuid4())
|
---|
29 | elif self.version==1:
|
---|
30 | return unicode(uuid.uuid1(self.node, self.clock_seq))
|
---|
31 | elif self.version==3:
|
---|
32 | return unicode(uuid.uuid3(self.namespace, self.name))
|
---|
33 | elif self.version==5:
|
---|
34 | return unicode(uuid.uuid5(self.namespace, self.name))
|
---|
35 | else:
|
---|
36 | return super(UUIDField, self).pre_save(model_instance, add)
|
---|
37 |
|
---|