10

I have the queryset like this

qs = User.objects.all()

I am converting to dict like this

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

but instead of username i want to get the string representation.

something like

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

user3214546
  • 6,523
  • 13
  • 51
  • 98

1 Answers1

9

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

What you could do is:

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: on second thought, depending on how your string representation is computed, it may be possible to use annotate with query expressions to achieve the same result.

aumo
  • 5,344
  • 22
  • 25