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))
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With