| 1 |
import shortuuid |
| 2 |
import sys |
| 3 |
from django.db.models import CharField |
| 4 |
|
| 5 |
|
| 6 |
class ShortUUIDField(CharField): |
| 7 |
""" |
| 8 |
A field which stores a Short UUID value in base57 format. This may also have |
| 9 |
the Boolean attribute 'auto' which will set the value on initial save to a |
| 10 |
new UUID value (calculated using shortuuid's default (uuid4)). Note that while all |
| 11 |
UUIDs are expected to be unique we enforce this with a DB constraint. |
| 12 |
""" |
| 13 |
|
| 14 |
def __init__(self, auto=True, *args, **kwargs): |
| 15 |
self.auto = auto |
| 16 |
|
| 17 |
kwargs['max_length'] = 22 |
| 18 |
if auto: |
| 19 |
|
| 20 |
kwargs['editable'] = False |
| 21 |
kwargs['blank'] = True |
| 22 |
|
| 23 |
|
| 24 |
super(ShortUUIDField, self).__init__(*args, **kwargs) |
| 25 |
|
| 26 |
def pre_save(self, model_instance, add): |
| 27 |
""" |
| 28 |
This is used to ensure that we auto-set values if required. |
| 29 |
See CharField.pre_save |
| 30 |
""" |
| 31 |
value = super(ShortUUIDField, self).pre_save(model_instance, add) |
| 32 |
if self.auto and not value: |
| 33 |
|
| •34 |
value = str(shortuuid.uuid()) |
| 35 |
setattr(model_instance, self.attname, value) |
| 36 |
return value |
| 37 |
|
| 38 |
def formfield(self, **kwargs): |
| 39 |
if self.auto: |
| 40 |
return None |
| 41 |
return super(ShortUUIDField, self).formfield(**kwargs) |
| 42 |
|
| 43 |
try: |
| 44 |
from south.modelsinspector import add_introspection_rules |
| 45 |
add_introspection_rules([], [r"^shortuuidfield\.fields\.ShortUUIDField"]) |
| 46 |
except ImportError: |
| 47 |
pass |