14

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.

1 Answer 1

39

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

Sign up to request clarification or add additional context in comments.

2 Comments

Brilliant! Could you please briefly explain why * works here?
@alexsalo That's a built-in python feature. I've added a link to the docs in my answer.

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.