Home > Enterprise >  Filtering by UUID in Django Admin
Filtering by UUID in Django Admin

Time:01-27

I have the following model:

class MyModel(models.Models):
    uuid = models.UUIDField(default=uuid.uuid4, db_index=True, editable=False, unique=True)
    name = models.CharField(max_length=200)

In my django admin, I have the following search_fields:

search_fields = ["uuid__exact", "name"]

This should translate to the following query:

MyModel.objects.filter(Q(uuid__exact=query) | Q(name__icontains=query))

However, running that query throws the following error:

ValidationError: ['“test name” is not a valid UUID.']

How do I prevent the uuid portion of the query from throwing a ValidationError? I want to be able to search my model by either the uuid or the name field in the django admin.

CodePudding user response:

Something like this should help:

class Cast(Func):
function = "CAST"
template = "%(function)s(%(expressions)s AS varchar)"
Group.objects.annotate(sid=Cast(id)).filter(sid__startswith='000')

I'm not sure if UUIDFields are searchable. One you could do this would be to have a property or an annotated field in your model that contains the string representation of the UUID.

CodePudding user response:

Since test name is not a valid uuid. So you can check your query if it is a valid uuid or not before using it in filter

You can use try-except and if ValueError occurs then filter by only name as

import uuid
from django.db.models import Q

filtered_data = None
try:
    uuid = uuid.UUID(query)
    filtered_data  = MyModel.objects.filter(Q(uuid__exact=query) | Q(name__icontains=query))
except ValueError:
    filtered_data  = MyModel.objects.filter(Q(name__icontains=query))

Or append Q objects as

import uuid
from django.db.models import Q

valid_query = Q(name__icontains=query)
try:
    uuid = uuid.UUID(query)
    valid_query |= Q(uuid)
except ValueError:
    pass

MyModel.objects.filter(valid_query)
    
  •  Tags:  
  • Related