14

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))

2 Answers 2

30

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Is there any reason for using a TextField() instead of a CharField()? Intuitively, the latter would have seemed more appropriate to me, given that the length of a uuid is 36 characters at most... But maybe it doesn't matter at all in terms of performance?
10

You have a list of objects that you want to convert to a list of strings:

items = [str(o) for o in items]

The only way to achieve that transformation is to process each item.

The reason print(str(items)) doesn't do what you want is that converts the list object to a string (which print() does anyway) rather than each object in the list.

4 Comments

ok, I already got items = [str(o) for o in items] but is there no way at all?
Why do you want something else?
Good question, I'm not sure it just seems inefficient but I have no base for that statement.
This may be an XY Problem. Why do you want to convert your list of UUIDs to a list of strings? Any such conversion will be O(n) and thus "slow" for large amounts of data. It looks like you may be using django, so if you really want your data to be strings then there may be a different way of modeling it (in django and/or the database) as strings.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.