noobzie
noobzie

Reputation: 1139

Python: Best approach to storing object state in database?

I need to store instances (or at least their state) in a database. The idea is that I should be able to re-create the instance on demand. Since I define the classes, I can choose how I would like to store the data.

Consider the following diagram, inheritance diagram:

                    A
                   / \
                  B   C
                 /\   /\
                D  E F  ...

The idea is that the instance can belong to any of those classes and can itself store other objects (that I have completely design control over).

My first thought is to store the state exclusively in a dictionary, dump the dictionary into a json and store it in the database. At run time, load json from the database convert it to dictionary, create an object passing in the dictionary that get's setup and so on...

I'm not sure if that is a good approach, and also if there are any other issues that might crop up. I already came across one, where if you use myobj.dict you don't actually get all the class' parent's attributes though...

Any suggestions?

Upvotes: 3

Views: 4910

Answers (3)

gomad
gomad

Reputation: 1039

There are several approaches. I don't really think we can tell you from the information you've provided what the best approach for you is.

These are the approaches I can think of off the top of my head. Only you can determine which one(s) fit your requirements and intention best.

Upvotes: 4

Raymond Hettinger
Raymond Hettinger

Reputation: 226171

The shelve module is the easiest way to get started with storing instances retrievable by a key. It automatically pickles and unpickles for you and takes care of the reading and writing to a file.

Upvotes: 2

Danish
Danish

Reputation: 3798

My suggestion would be to design an Object model around your states and use an ORM toolkit for Python. Several are mentioned here - What are some good Python ORM solutions?

I believe its not best to re-invent the wheel. You can use an ORM toolkit to either store the states or the actual object instance tree itself.

Upvotes: 0

Related Questions