Hello Django users,

I've recently upgraded the Django version from 2.2 to 3.2 in a project at
work. In this project, we've been using a custom version of UUIDField since
version 1.x without issues. The purpose of this field is to persist the
full UUIDs with dashes into the database (MySQL char(36)).

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)

Now the problem introduced with 3.2 is that filtering by this field doesn't
work properly. If I try to filter by a full UUID (with or without dashes)
it returns an empty QuerySet. If I provide only one part of the UUID (i.e.
one group of characters between the dashes) it works just fine.

Python 3.6.9 (default, Mar 15 2022, 13:55:28)
[GCC 8.4.0] on linuxType "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 []>
>>>

Here's a little Github Gist
<https://gist.github.com/milonoir/080ecfe1d0fa52df0a0c4a6ab265dde0> where I
uploaded a simplified model.py and admin.py along with the UUIDField. This
is what I used above in the python shell. Any help would be appreciated, I
couldn't figure out how to fix it.

(PS: I also raised this in StackOverflow
<https://stackoverflow.com/questions/72101751/filtering-by-custom-uuidfield-got-broken-with-django-3-2-upgrade>
just in case you came across with it.)

Cheers,
Milan

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/CAEE8kq5Kgo4pY9y93wj1dEzoGyDf_JHoPYqdtYfGi_1jWHX7%2Bg%40mail.gmail.com.

Reply via email to