Skip to content

Instantly share code, notes, and snippets.

@danigosa
Last active December 15, 2015 11:29
Show Gist options
  • Save danigosa/5253504 to your computer and use it in GitHub Desktop.
Save danigosa/5253504 to your computer and use it in GitHub Desktop.
MSSQL UUID Field compatible for the django-jsonfield app. It makes migrations from POstgres to MSSQL work :)
from uuidfield.fields import StringUUID
from django.utils.encoding import smart_unicode
__author__ = 'danigosa'
from uuidfield import UUIDField
class MssqlUUIDField(UUIDField):
"""
A field which stores a UUID value in hex format. This may also have
the Boolean attribute 'auto' which will set the value on initial save to a
new UUID value (calculated using the UUID1 method). Note that while all
UUIDs are expected to be unique we enforce this with a DB constraint.
"""
def __init__(self, version=4, node=None, clock_seq=None,
namespace=None, name=None, auto=False, *args, **kwargs):
assert version in (1, 3, 4, 5), "UUID version %s is not supported." % version
self.auto = auto
self.version = version
# We store UUIDs in hex format, which is fixed at 32 characters.
# MSSQL UUIDs as TEXT: we put 36 chars to enable migration from Postgresql UUID
kwargs['max_length'] = 36
if auto:
# Do not let the user edit UUIDs if they are auto-assigned.
kwargs['editable'] = False
kwargs['blank'] = True
kwargs['unique'] = True
if version == 1:
self.node, self.clock_seq = node, clock_seq
elif version in (3, 5):
self.namespace, self.name = namespace, name
super(UUIDField, self).__init__(*args, **kwargs)
def to_python(self, value):
"""
Returns a ``StringUUID`` instance from the value returned by the
database. This doesn't use uuid.UUID directly for backwards
compatibility, as ``StringUUID`` implements ``__unicode__`` with
``uuid.UUID.hex()``.
"""
if not value:
return None
# attempt to parse a UUID including cases in which value is a UUID
# instance already to be able to get our StringUUID in.
#FIX: Must strip string because it adds 4 spaces to fill the length
return StringUUID(smart_unicode(value.strip()))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment