How can I get a string representation from a request in django

I have a request like this

qs = User.objects.all()

I convert to dict so

qs.values('id', 'username')

but instead of the username, I want to get a string representation.

sort of

qs.values('id', '__str__')

+5
source share
1 answer

You cannot, values can only retrieve the values ​​stored in the database, the string representation is not stored in the database, it is computed in Python.

What can you do:

 qs = User.objects.all() # Compute the values list "manually". data = [{'id': user.id, '__str__': str(user)} for user in qs] # You may use a generator to not store the whole data in memory, # it may make sense or not depending on the use you make # of the data afterward. data = ({'id': user.id, '__str__': str(user)} for user in qs) 

Edit: The second time, depending on how your string representation is calculated, you can use annotate with the query expression to achieve the same result.

+4
source

All Articles