# MS SQL UUID like id

**URL:** <https://forum.djangoproject.com/t/ms-sql-uuid-like-id/25636>\
**Category:** Using the ORM\
**Created:** [November 25, 2023, 7:28am UTC](https://forum.djangoproject.com/t/ms-sql-uuid-like-id/25636 "2023-11-25T07:28:19Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![ThaiBee](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/thaibee/32/7054_2.png) [@ThaiBee](https://forum.djangoproject.com/u/ThaiBee)\
**Post date:** [November 25, 2023, 7:28am UTC](https://forum.djangoproject.com/t/ms-sql-uuid-like-id/25636/1 "2023-11-25T07:28:19Z")

</div>

I have an existing project with MS SQL. and should continue it. on existing projects all table IDs in the database use UUID.  
I found on the net how to use an MS SQL field. it’s working well. but have one problem. when I create a new object and save it - the object should receive a new ID from the database. but it doesn’t happen.  
Someone can help me? what needs to be rewritten to receive the ID after saving?  
thanks in advance!

> Blockquote  
> from uuid import UUID  
> from django.db.models import UUIDField  
> from django.core.exceptions import ValidationError  
> class MssqlUUIDField(UUIDField):  
> def **init** (self, \*args, \*\*kwargs):  
> kwargs[‘max\_length’] = 36  
> super(UUIDField, self). **init** (\*args, \*\*kwargs)

```
def db_type(self, connection):
    if self.primary_key:
        return 'uniqueidentifier default (newid())'
    else:
        return 'uniqueidentifier'

def contribute_to_class(self, cls, name, **kwargs):
    assert not self.primary_key or (
            self.primary_key and not cls._meta.auto_field), "A model can't have more than one AutoField."
    super().contribute_to_class(cls, name, **kwargs)
    if self.primary_key:
        cls._meta.auto_field = self

def get_db_prep_value(self, value, connection, prepared=False):
    if value is None:
        return None
    if not isinstance(value, UUID):
        value = self.to_python(value)
    return str(value)

def rel_db_type(self, connection):
    return 'uniqueidentifier'

def from_db_value(self, value, expression, connection):
    return self._to_uuid(value)

def to_python(self, value):
    return self._to_uuid(value)

def _to_uuid(self, value):
    if value is not None and not isinstance(value, UUID):
        try:
            return UUID(value)
        except (AttributeError, ValueError):
            raise ValidationError(
                self.error_messages['invalid'],
                code='invalid',
                params={'value': value},
            )
    return value

```

> Blockquote  
> class Category(models.Model):  
> id = MssqlUUIDField(primary\_key=True, db\_column=‘id’, default=None, editable=False)  
> title = models.CharField(max\_length=255, db\_column=‘title’)  
> created\_at = models.DateTimeField(default=timezone.now, db\_column=‘created\_at’)  
> def **str** (self):  
> return self.title
