How to limit columns returned by Django query?

DjangoOrm

Django Problem Overview


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

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

Django Solutions


Solution 1 - Django

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.

Solution 2 - Django

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionphilgo20View Question on Stackoverflow
Solution 1 - DjangoDaniel RosemanView Answer on Stackoverflow
Solution 2 - DjangoIan ClellandView Answer on Stackoverflow