I have a Django project that I've recently upgraded from Django 2.2 to 3.2. In this project, I use a custom UUIDField that saves UUIDs to MySQL as char(36) in the following format: 12345678-1234-5678-1234-567812345678.
import uuid
from django.db import models
class UUIDField(models.UUIDField):
"""
Overrides Django UUIDField to store full UUID's including dashes.
"""
def __init__(self, verbose_name=None, **kwargs):
super().__init__(verbose_name, **kwargs)
self.max_length = 36
def get_internal_type(self):
return "CharField"
def get_db_prep_value(self, value, connection, prepared=False):
if value is None:
return None
if not isinstance(value, uuid.UUID):
try:
value = uuid.UUID(value)
except AttributeError:
raise TypeError(self.error_messages['invalid'] % {'value': value})
if connection.features.has_native_uuid_field:
return value
return str(value)
After the upgrade, I noticed that searching for full UUIDs didn't work anymore. If I only provide the first part of the UUID (up to the first character after the first hyphen) it works as expected.
Python 3.6.9 (default, Mar 15 2022, 13:55:28)
[GCC 8.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from foobar.foo.models import Foo
>>>
>>> Foo.objects.all()
<QuerySet [<Foo: Foo object (34c46fe8-caf0-11ec-bdb9-482ae362a4c0)>]>
>>>
>>> Foo.objects.filter(id__icontains='34c46fe8-caf0-11ec-bdb9-482ae362a4c0')
<QuerySet []>
>>>
>>> Foo.objects.filter(id__icontains='34c46fe8-')
<QuerySet [<Foo: Foo object (34c46fe8-caf0-11ec-bdb9-482ae362a4c0)>]>
>>>
>>> Foo.objects.filter(id__icontains='34c46fe8-c')
<QuerySet []>
>>>
I've played with the UUIDField methods, but I can't seem to figure out what went wrong. Here's a link to a Gist using a simplified model where I got the above shell example from.