Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass list of fields to QuerySet.values( )

Is there a way I can pass a list of fields to be retrieved by the QuerySet.values(). I have a model and I want to retrieve different sets of fields from it on different occasions.

like image 766
shreyj Avatar asked Oct 05 '12 06:10

shreyj


People also ask

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

Can I filter a QuerySet Django?

The filter() method is used to filter you search, and allows you to return only the rows that matches the search term.

What is QuerySet annotate?

In simpler terms, annotate allows us to add a pseudo field to our queryset. This field can then further be used for filter lookups or ordering.\ Ex: Suppose you want to all the Books along with the total number of chapters present in each one, then you could use annotate as follows: Simple annotate example.


1 Answers

You can use the * operator to expand a list out into separate arguments when passed to a function, as described here in the Python tutorial.

>>> qs = User.objects.all()
>>> values = ['first_name', 'email']
>>> qs.values(*values)

yields

[{'first_name': u'aaaa', 'email': u'[email protected]'}, 
 {'first_name': u'', 'email': u'[email protected]'}, 
 {'first_name': u'', 'email': u'[email protected]'},
 '...(remaining elements truncated)...']

(I further truncated the output for brevity).

like image 172
dokkaebi Avatar answered Oct 27 '22 18:10

dokkaebi