Skip to content
thesarfo

Note

Selecting Specific Fields

Restricting a query to specific columns with values(), values_list(), only(), and its opposite defer().

views 0

Assuming you have a bunch of data and youre not interested in all of them. Eg the description column of your customers table is too long and you’re only interesed in the customer name.

You can select only the customer name field using a method called values()

queryset = Customer.objects.values('customer_name')
# This returns only the customer name

You can also read from a related field

queryset = Customer.objects.values('customer_name', 'collection__id')

This returns the customer name alright, but also reads into the collection table and returns it’s id column. However if you render this queryset in the browser, it is a dictionary. If you use the values_list() method, it returns a tuple instead of a dictionary.

There is another method called only() which also makes you specify the specific field you want to read from the database.

queryset = Product.objects.only('id', 'title')
# This method differs from the values() method such that the only() method returns the instance
# of the object whereas values() returns a dictionary

The opposite of the only() method is the defer() method which does not render the field passed in as an argument. For instance, you want to render everything about a product without its description, so you defer the description field with the defer() method.

queryset = Product.objects.only('description')