[storm] Lazy value loading
Thomas Hervé
thomas at canonical.com
Fri Oct 24 13:36:18 BST 2008
Le vendredi 24 octobre 2008 à 14:16 +0200, Adrian Adamiak a écrit :
> Hi. I've got a question about lazy value loading.
>
> Let's say that I have an ORM mapping for table 'book':
>
> class Book(object):
> __storm_table__ = "book"
> id = Int(primary=True)
> author = Unicode()
> title = Unicode()
> contents = Unicode() # this can be big
>
> Sometimes I need to display a list of titles and authors of all books, so I use:
>
> books = store.find(Book)
>
> Unfortunately this produces query which loads all fields, including
> 'contents', which is unnecessary and takes a lot of time. I'd like to
> make the 'contents' field lazy, i.e.
>
> contents = Unicode(lazy=True) # (in Book class definition)
>
> so that it would load only after I access this field (i.e.
> books[0].contents). Is it possible?
The way I'd do it would be like that:
class Book(object):
__storm_table__ = "book"
id = Int(primary=True)
author = Unicode()
title = Unicode()
@property
def contents(self):
return Store.of(self).execute("SELECT contents FROM book WHERE
id = ?", (self.id,)).get_one()[0]
This way you're sure that you don't get through all Python code for
nothing. It's in no way optimal, but it works.
--
Thomas
More information about the storm
mailing list