tags:

views:

63

answers:

2

Hi all,

I have a small question regarding the Django database query system. I have seen that most of the code we find over internet, forums or even in a tutorials, it uses queries like :

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

but this 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?

Please suggest.

Thanks in advance.

+2  A: 

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.

Ignacio Vazquez-Abrams
A: 

if you need just the values as a dictionary use objects.values(''). Its also faster.

see docs: http://docs.djangoproject.com/en/dev/ref/models/querysets/#values-fields

aviah