Skip to content

Instantly share code, notes, and snippets.

@ydaniv
Created December 1, 2015 13:11
Show Gist options
  • Save ydaniv/349ffff380f5a530e795 to your computer and use it in GitHub Desktop.
Save ydaniv/349ffff380f5a530e795 to your computer and use it in GitHub Desktop.
Django UUIDField with primary key and default value that doesn't break `if self.id` checks inside `save()`
import uuid
from django.db import models
from django.utils.encoding import force_text as force_unicode
class DefaultUUIDField(models.UUIDField):
def __init__(self, *args, **kwargs):
kwargs['blank'] = True
kwargs.setdefault('editable', False)
super(DefaultUUIDField, self).__init__(*args, **kwargs)
def pre_save(self, model_instance, add):
value = super(DefaultUUIDField, self).pre_save(model_instance, add)
if add and value is None:
value = force_unicode(self.create_uuid())
setattr(model_instance, self.attname, value)
return value
else:
if not value:
value = force_unicode(self.create_uuid())
setattr(model_instance, self.attname, value)
return value
@staticmethod
def create_uuid():
return uuid.uuid4()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment