I've created a model, and I'm rendering the default/unmodified model form for it. This alone generates 64 SQL queries because it has quite a few foreign keys, and those in turn have more foreign keys.
Is it possible to force it to always (by default) perform a select_related
every time one of these models are returned?
You can create a custom manager, and simply override
get_queryset
for it to apply everywhere. For example:(Prior to Django 1.6, it was
get_query_set
).Here's also a fun trick:
Then you can re-use the manager easily between model classes. As an example use case, this would be appropriate if you had a
__unicode__
method on the model which rendered a string that included some information from a related model (or anything else that meant a related model was almost always required)....and if you really want to get wacky, here's a more generalized version. It allows you to call any sequence of methods on the default queryset with any combination of
args
orkwargs
. There might be some errors in the code, but you get the idea.The python-mock-inspired
MethodCalls
object is an attempt at making the API more natural. Some might find that a bit confusing. If so, you could sub out that code for an__init__
arg or kwarg that just accepts a tuple of method call information.Create a custom
models.Manager
and override all the methods (filter
,get
etc.) and append select_related onto every query. Then set this manager as theobjects
attribute on the model.I would recommend just going through your code and adding the
select_related
where needed, because doing select_related on everything is going to cause some serious performance issues down the line (and it wouldn't be entirely clear where it's coming from).