Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python change UUID object to string representation list

Tags:

python

When retrieving a queryset with values_list of PKs there are of type UUIDField Django gives you a list of UUIDField objects and NOT a list of string UUIDs.

For example, the following gives me a query set:

items = Item.objects.values_list('id', flat=True).filter()

Where the output of print(items) is:

[UUID('00c8aa9e-2f61-4bac-320c-ab26b8fb1de9')]

But I would like the list to be a string representation of of UUID's i.e.

 ['00c8aa9e-2f61-4bac-320c-ab26b8fb1de9']

I can do this with each object individual in a loop but I want to change the whole queryset. Is this possible?

I have tried:

print(str(items))
like image 223
Prometheus Avatar asked Nov 30 '22 23:11

Prometheus


1 Answers

You can solve this in a Django specific way using the database instead of bringing the solution into memory.

Django now has the Cast function which can be imported from django.db.model.functions.

It can be then used in a query:

from django.db.models import TextField
from django.db.models.functions import Cast


items = Item.objects.annotate(str_id=Cast('id', output_field=TextField())).values_list('str_id', flat=True)
like image 122
Andrew Miller Avatar answered Dec 05 '22 14:12

Andrew Miller