[Django]-Django Queryset only() and defer()

38đź‘Ť

âś…

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.

29đź‘Ť

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

  • you want either optimization, by avoiding unnecessary column fetching

  • you are implementing views in your python code. Eg.Admin have to
    shown X no. of cols, User have to be shown Y no. of cols, Visitor
    have to be shown z no of cols.

Leave a comment