Reputation: 18246
I have something like this:
class A ():
[...]
class B ():
def __init__(self):
self.fubar = A()
And I would like to store B into a database via SQLAlchemy. I think that I need to define both A
and B
as two different tables -- mapping all the other properties of A
and B
appropriately. Then, I need to map A
to B
as a property but I am not sure how to do that.
Is my thinking good or did I miss something? Any idea what functions call I am missing -- or what page of the documentation covers it?
Thanks
Upvotes: 0
Views: 72
Reputation: 67147
You should indeed define two database entities, A
and B
, and a 1:1 or 1:n relationship between those two:
Base = declarative_base()
class A(Base):
__tablename__ = 'a'
id = Column(Integer, primary_key=True)
class B(Base):
__tablename__ = 'b'
id = Column(Integer, primary_key=True)
a_id = Column(Integer, ForeignKey('a.id'))
foobar = relationship('A')
def __init__(self):
self.foobar = A()
For a real-world example, read the ORM tutorial, where your class A
is named User
and B
Address
.
Upvotes: 1