Skip to content

Instantly share code, notes, and snippets.

@hellysmile
Created August 17, 2016 08:02
Show Gist options
  • Save hellysmile/12e9c052d9ec92881d83471808f001c7 to your computer and use it in GitHub Desktop.
Save hellysmile/12e9c052d9ec92881d83471808f001c7 to your computer and use it in GitHub Desktop.
import uuid
from django.db import models
class UUIDField(
models.UUIDField
):
def __init__(self, *args, **kwargs):
self.version = kwargs.pop('version', 1)
self.auto = kwargs.pop('auto', True)
if self.auto or kwargs.get('default'):
kwargs['blank'] = True
kwargs.setdefault('editable', False)
super().__init__(*args, **kwargs)
def generate_uuid(self):
if self.version == 4:
return uuid.uuid4()
elif self.version == 1:
return uuid.uuid1()
else:
raise ImproperlyConfigured
def set_default(self, model_instance):
value = self.generate_uuid()
setattr(model_instance, self.attname, value)
return value
def pre_save(self, model_instance, add):
value = getattr(model_instance, self.attname)
if self.auto and add and value is None:
value = self.set_default(model_instance)
else:
if self.auto and not value:
value = self.set_default(model_instance)
return value
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment