Django - Prevent automatic related table fetch -


how can prevent django, testing purposes, automatically fetching related tables not specified in select_related() call during intial query?

i have large application make significant use of select_related() bring in related model data during each original query. select_related() calls used specify specific related models, rather relying on default, e.g. select_related('foo', 'bar', 'foo__bar')

as application has grown, select_related calls haven't kept up, leaving number of scenarios django happily , kindly goes running off database fetch related model rows. increases number of database hits, don't want.

i've had success in tracking these down checking queries generated using django.db.connection.queries collection, remain unsolved.

i've tried find suitable patch location in django code raise exception in scenario, making tracking easier, tend lost in code.

thanks.

after more digging, i've found place in code this.

the file in question django/db/models/fields/related.py

you need insert 2 lines file.

locate class "singlerelatedobjectdescriptor". need change function __get__() follows:

def __get__(self, instance, instance_type=none):     if instance none:         return self     try:         return getattr(instance, self.cache_name)     except attributeerror:         raise exception("automated database fetch on %s.%s" % (instance._meta.object_name, self.related.get_accessor_name()))         # leave old code here when revert! 

similarly, in class "reversesinglerelatedobjectdescriptor" further down code, again need change __get__() to:

def __get__(self, instance, instance_type=none):     if instance none:         return self      cache_name = self.field.get_cache_name()     try:         return getattr(instance, cache_name)     except attributeerror:         raise exception("automated database fetch on %s.%s" % (instance._meta.object_name, self.field.name))         # beware: % parameters different previous class         # leave old code here when revert 

once you've done this, you'll find django raises exception every time performs automatic database lookup. pretty annoying when first start, track down pesky database lookups. obviously, when you've found them all, it's best revert database code normal. suggest using during debugging/performance investigation phase , not in live production code!


Comments

Popular posts from this blog

apache - Add omitted ? to URLs -

redirect - bbPress Forum - rewrite to wwww.mysite prohibits login -

php - How can I stop spam on my custom forum/blog? -