[Django]-How to limit columns returned by Django query?

102πŸ‘

βœ…

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.

44πŸ‘

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

πŸ‘€Ian Clelland

2πŸ‘

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.

πŸ‘€John

Leave a comment