SQLalchemy with nested class
I have a rather complex object that takes a few other objects as its members. Something like this:
from engine import engine
Class Car(objec开发者_运维知识库t):
def __init__(self,engine_type):
self.engine=engine(engine_type)
Is there a pain-free approach to map such nested definitions to a database, using SQLAlchemy for example?
Thanks for your help. I am learning SQLAlchemy and working with ORMS.
It's not much clear what you're trying to accomplish. If I understood, you are trying to define Car model with engine attribute that points to another Engine model, and by creating Car object with engine_type, the code should either:
- create Engine object with engine type if it doesn't exist
- load the Engine object with engine type if exists
and then assign it to the Car object.
If so, you should do the following.
class Engine(object):
def __init__(self, engine_type):
self.engine_type
@staticmethod
def load(engine_type):
return session.query(Engine)\
.filter(engine_type==engine_type).one()
class Car(object):
def __init__(self, engine_type):
try:
engine = Engine.load(engine_type)
except NoResultsFound:
engine = Engine(session_type)
session.add(engine)
self.engine=engine
You'll need to define to create the 'engine' relationship on the Car mapper yourself, and also you'll need code tweaking to enable scope of the session object where needed.
精彩评论