Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to limit columns returned by Django query?

Tags:

orm

django

That seems simple enough, but all Django Queries seems to be 'SELECT *'

How do I build a query returning only a subset of fields ?

like image 754
philgo20 Avatar asked Mar 15 '10 17:03

philgo20


People also ask

What is reduce in Django?

The Python docs describe reduce as: Applying a function of two arguments cumulatively to the items of iterable, from left to right, so as to reduce the iterable to a single value.

What does .values do in Django?

Django values_list() is an optimization to grab specific data from the database instead of building and loading the entire model instance.

What does objects all () return in Django?

all() Returns a copy of the current QuerySet (or QuerySet subclass). This can be useful in situations where you might want to pass in either a model manager or a QuerySet and do further filtering on the result.


2 Answers

In Django 1.1 onwards, you can use defer('col1', 'col2') to exclude columns from the query, or only('col1', 'col2') to only get a specific set of columns. See the documentation.

values does something slightly different - it only gets the columns you specify, but it returns a list of dictionaries rather than a set of model instances.

like image 78
Daniel Roseman Avatar answered Oct 13 '22 07:10

Daniel Roseman


Append a .values("column1", "column2", ...) to your query

like image 39
Ian Clelland Avatar answered Oct 13 '22 07:10

Ian Clelland