Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Queryset only() and defer()

Tags:

In the real world, how often do people use QuerySet methods like defer() and only()? I guess I handnt really heard much about them and only recently have I came across these methods.

See Docs here. https://docs.djangoproject.com/en/dev/ref/models/querysets/

like image 863
a.m. Avatar asked Mar 08 '13 01:03

a.m.


People also ask

What is defer in Django?

defer() and only() are somewhat opposite of each other. Both receives list of field_names . defer() will not query, list of columns, passed to it as argument. On Contrary to it, only() will query, only list of columns, passed to it as argument. Both are used in a scenario, where.

What is Django Queryset?

A QuerySet is a collection of data from a database. A QuerySet is built up as a list of objects. QuerySets makes it easier to get the data you actually need, by allowing you to filter and order the data.

Why are QuerySets considered lazy?

This is because a Django QuerySet is a lazy object. It contains all of the information it needs to populate itself from the database, but will not actually do so until the information is needed.


1 Answers

These methods are mostly of use when optimizing performance of your application.

Generally speaking, if you are not having performance problems, you don't need to optimize. And if you don't need to optimize, you don't need these functions. This is a case with a lot of advanced QuerySet features, such as select_related or prefetch_related.

As for "how often they are used in the real world", that isn't really an answerable question. They are used when they're needed. If you don't need them, don't use them.

like image 132
Andrew Gorcester Avatar answered Oct 05 '22 09:10

Andrew Gorcester