Serializing entity instances using pickle

Pony allows pickling entity instances, query results and collections. You might want to use it if you want to cache entity instances in an external cache (e.g. memcache). When Pony pickles entity instances, it saves all attributes except collections in order to avoid pickling a large set of data. If you need to pickle a collection attribute, you must pickle it separately. Example:

  1. >>> from pony.orm.examples.estore import *
  2. >>> products = select(p for p in Product if p.price > 100)[:]
  3. >>> products
  4. [Product[1], Product[2], Product[6]]
  5. >>> import cPickle
  6. >>> pickled_data = cPickle.dumps(products)

Now we can put the pickled data to a cache. Later, when we need our instances again, we can unpickle it:

  1. >>> products = cPickle.loads(pickled_data)
  2. >>> products
  3. [Product[1], Product[2], Product[6]]

You can use pickling for storing objects in an external cache for improving application performance. When you unpickle objects, Pony adds them to the current db_session() as if they were just loaded from the database. Pony doesn’t check if objects hold the same state in the database.