Skip to content

Instantly share code, notes, and snippets.

@gonzaloamadio
Forked from hellysmile/model_fields.py
Created April 30, 2021 15:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gonzaloamadio/162781ecd178f0d3c067f5f26ad95242 to your computer and use it in GitHub Desktop.
Save gonzaloamadio/162781ecd178f0d3c067f5f26ad95242 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