Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i get the string representation from queryset in django

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

like image 985
user3214546 Avatar asked May 03 '15 09:05

user3214546


People also ask

What is __ Str__ in Django?

The __str__ method just tells Django what to print when it needs to print out an instance of the any model. It is also what lets your admin panel, go from this. Note: how objects are just plainly numbered. to this. .

How do you get or view all the items in a model in Django?

The simplest way you can get the list of objects of an attribute is to first get a query-set of that attribute alone using values_list then converting the django query-set to a python set using set() and finally to a list using list() .

What does QuerySet []> mean?

A QuerySet is a collection of data from a database. A QuerySet is built up as a list of objects. QuerySets makes it easier to get the data you actually need, by allowing you to filter and order the data. In this tutorial we will be querying data from the Members table.


1 Answers

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.

like image 136
aumo Avatar answered Oct 20 '22 01:10

aumo