Django - Prevent table auto-binding

How can I prevent Django from automatically retrieving related tables for testing purposes that are not specified in the select_related () call during an internal query?

I have a great application where I use select_related () to enter related model data during each original request. All calls to select_related () are used to specify specific related models, rather than relying on the default value, for example. select_related ('foo', 'bar', 'foo__bar')

As the application grew, select_related calls weren’t fully preserved, leaving a series of scenarios where Django happily and kindly sent to the database to retrieve the associated row model. This significantly increases the number of database calls that I obviously do not want.

I had some success in tracking these errors, checking the requests generated by the django.db.connection.queries collection, but some remain unresolved.

I tried to find a suitable place for the patch in the django code to raise an exception in this scenario, which makes tracking a lot easier, but tends to get lost in the code.

Thank.

+3
source share
2 answers

After some extra digging, I found a place in the code for this.

django/db/models/fields/related.py

.

"SingleRelatedObjectDescriptor". __get __() :

def __get__(self, instance, instance_type=None):
    if instance is 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 the old code here for when you revert!

, "ReverseSingleRelatedObjectDescriptor" __get __() :

def __get__(self, instance, instance_type=None):
    if instance is 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 are different to previous class
        # leave old code here for when you revert

, , Django , . , , . , , , . /, !

+1

, , , ? , .

select_related , , null=True. , FK, .

0

Source: https://habr.com/ru/post/1793071/


All Articles