Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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?

like image 704
Ankit Jaiswal Avatar asked Jun 11 '10 04:06

Ankit Jaiswal


People also ask

What is __ GTE in Django?

The __lte lookup [Django-doc] means that you constrain the field that is should be less than or equal to the given value, whereas the __gte lookup [Django-doc] means that the field is greater than or equal to the given value. So for example: MyModel.objects.

How do I get unique QuerySet in Django?

If you want to get distinct objects, instead of values, then remove flat=True from the above query, and use values() instead of values_list(). In the above code, we add distinct() at the end of queryset to get distinct values.


1 Answers

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.

like image 51
Ignacio Vazquez-Abrams Avatar answered Sep 28 '22 06:09

Ignacio Vazquez-Abrams