Package pyperry :: Package processors :: Module preload_associations :: Class PreloadAssociations
[frames] | no frames]

Class PreloadAssociations

source code

object --+
         |
        PreloadAssociations

The PreloadAssociations processor looks for any association ids given in a query's 'includes' value and eager loads those associations. The purpose of eager loading (or preloading) is to reduce the number of adapter calls needed to retrieve records in an association, which can yield a significant performance boost if you have a query where you are using many associated models.

For example, let's assume you are writing a news website and you have a Reporter model and a Story model where each Reporter has many Stories. Now suppose you want to display a list all reporters and their stories on the screen grouped by the reporter's name, you could do this like:

   reporters = Reporter.order('name').all()
   for reporter in reporters:
       print reporter.name
       for story in reporter.stories():
           print " %s" % story.title

If your news website has 20 reporters, you have just executed 1 adapter call to retrieve the list of reporters and then 20 more adapter calls, one for each reporter's stories, for a total of 21 adapter calls. The problem with having too many adapter calls is that typically adapters must read data from a server on the network, which causes your program to wait while the server generates a response and sends it over the network.

Instead, you can achieve the same results in 2 queries by using the includes method in your query to trigger association preloading. In this modified example, we simple add .includes('stories') to our query, and all of the stories for every report will be retrieved with only one additional adapter call:

   reporters = Reporter.order('name').includes('stories').all()
   for reporter in reporters:
       print reporter.name
       for story in reporter.stories():
           print " - %s" % story.title
Instance Methods
 
__init__(self, next, options={})
x.__init__(...) initializes x; see x.__class__.__doc__ for signature
source code
 
__call__(self, **kwargs) source code
 
do_preload(self, results, **kwargs)
Eager loads the records for each association in the query's includes.
source code
 
add_records_to_scope(self, association, records, result)
Caches the eager loaded records on the matching target model and association along with the corresponding scope.
source code

Inherited from object: __delattr__, __format__, __getattribute__, __hash__, __new__, __reduce__, __reduce_ex__, __repr__, __setattr__, __sizeof__, __str__, __subclasshook__

Properties

Inherited from object: __class__

Method Details

__init__(self, next, options={})
(Constructor)

source code 

x.__init__(...) initializes x; see x.__class__.__doc__ for signature

Overrides: object.__init__
(inherited documentation)