How to fetch only specific columns of a table in django?


I have seen that queries like :

user = User.objects.all() or User.objects.filter(username = username)

will fetch all the columns of the table even if we do not need all the columns. Do we have a better way of writing a database query? and if yes why do we not see that code most often?

6/2/2016 9:56:31 AM

Accepted Answer

QuerySet.only() and QuerySet.defer() can be used to refine which fields the ORM will pull, deferring the others until the appropriate attributes on the models are accessed.

7/23/2015 5:01:59 PM

With django 1.8: use the values_list

Entry.objects.values_list('id', 'headline')

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow