philgo20
philgo20

Reputation: 6517

How to limit columns returned by Django query?

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

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

Upvotes: 84

Views: 51784

Answers (3)

John
John

Reputation: 88

The accepted answer advises defer and only, however the docs discourage this in most cases.

only use defer() when you cannot, at queryset load time, determine if you will need the extra fields or not. If you are frequently loading and using a particular subset of your data, the best choice you can make is to normalize your models and put the non-loaded data into a separate model (and database table). If the columns must stay in the one table for some reason, create a model with Meta.managed = False (see the managed attribute documentation) containing just the fields you normally need to load and use that where you might otherwise call defer(). This makes your code more explicit to the reader, is slightly faster and consumes a little less memory in the Python process.

Upvotes: 3

Daniel Roseman
Daniel Roseman

Reputation: 599530

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.

Upvotes: 105

Ian Clelland
Ian Clelland

Reputation: 44122

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

Upvotes: 44

Related Questions