165

I have a model Employees and I would like to have a QuerySet of all rows, but with some specific fields from each row, and not all fields.

I know how to query all rows from the table/model:

Employees.objects.all() 

I would like to know how to select fields for each of the Queryset element. How can I do that?

1
  • 1
    What do you mean by "and using only one"? A SELECT col instead of SELECT *? Commented Jun 12, 2016 at 21:29

10 Answers 10

282
Employees.objects.values_list('eng_name', flat=True) 

That creates a flat list of all eng_names. If you want more than one field per row, you can't do a flat list: this will create a list of tuples:

Employees.objects.values_list('eng_name', 'rank') 
Sign up to request clarification or add additional context in comments.

5 Comments

thanks for the answer, what if I want to select only 1 or more fields (not all)?
Sorry, I don't understand the question.
please share the document.that will helps to others
Does values_list return a dictionary similar values or an object?
'QuerySet' object has no attribute 'objects'
49

In addition to values_list as Daniel mentions you can also use only (or defer for the opposite effect) to get a queryset of objects only having their id and specified fields:

Employees.objects.only('eng_name') 

This will run a single query:

SELECT id, eng_name FROM employees 

3 Comments

This command is returning me all the fields for my Django version 2.1.3 and python version 3.6.2.
It will only fetch this one filed, but if you try to access other fields, a separate database query will be executed. So this is a good optimization technique, but make sure that you do not create these extra queries. Otherwise you will lose performance instead of gaining it.
The difference between only and values is only also fetches the id.
22

We can select required fields over values.

Employee.objects.all().values('eng_name','rank') 

3 Comments

After the query is run successfully, how to store the value of a field in a variable, eg. var_name = <query_name>.<field_name> ?
@user12379095 just simply like this: var_name = Employee.objects.all().values('eng_name','rank')
@user12379095 and then to use this var_name - for example: print all the employees names and rank, you can do this: for person in var_name: print(person['eng_name'] + " " + person['rank'])
9

Daniel's answer is right on the spot. If you want to query more than one field then do this:

Employee.objects.values_list('eng_name','rank') 

This will return list of tuples. You cannot use named=True when querying more than one field.

Moreover if you know that only one field exists with that info and you know the pk id then do this:

Employee.objects.values_list('eng_name','rank').get(pk=1) 

Comments

3

Oskar Persson's answer is the best way to handle it because makes it easier to pass the data to the context and treat it normally from the template as we get the object instances (easily iterable to get props) instead of a plain value list.

After that you can just easily get the wanted prop:

for employee in employees: print(employee.eng_name) 

Or in the template:

{% for employee in employees %} <p>{{ employee.eng_name }}</p> {% endfor %} 

Comments

2

You can use values_list alongside filter like so;

active_emps_first_name = Employees.objects.filter(active=True).values_list('first_name',flat=True) 

More details here

Comments

2
Employees.objects.filter().only('eng_name') 

This will give a QuerySet of all rows, but with only the specified fields. It does NOT give a list like the other answers above. It gives your the OBJECT INSTANCES. Watch out; it is objects.filter().only() NOT just objects.only()

It is similar to SQL Query:

SELECT eng_name FROM Employees; 

Comments

2
queryset = ModelName.objects.filter().only('field1', 'field2') 

Comments

1

You can also use list with field names

field_names = ['product_id', 'name', 'price', 'status'] results = ModelName.objects.all().values_list(*field_names) # or for example # results = ModelName.objects.all().values_list(*field_names, named=True) 

Comments

0

Summarising your options and what they return:

First objects.filter.only('field_1', 'field_2', 'field_3') returns a queryset of objects whose values can be accessed by obj.field_1:

[<Employee: id>, <Employee: id>, etc. ] 

Second objects.filter.values('field_1', 'field_2', 'field_3') returns a queryset of dictionaries containing field names and values:

[{'field_1': value, 'field_2': value, 'field_3': value}, etc. ] 

Finally objects.filter.values_list('field_1', 'field_2', 'field_3') returns a queryset of unpacked tuples containing only values:

[(value, value, value), etc. ] 

Choose one that best suits your application.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.