While working through the documentation from SQLAlchemy, I can't seem to get an understanding of the purpose of the relationship() function.
I have created a database with and without the relationship() mapping and see no difference in the table definitions at the db level. I also notice no effect on queries through the interactive prompt. No 'children' column is created on the table 'parent'. What is its purpose?
class Parent(Base):
__tablename__ = 'parent'
id = Column(Integer, primary_key=True)
children = relationship("Child", backref="parent")
class Child(Base):
__tablename__ = 'child'
id = Column(Integer, primary_key=True)
parent_id = Column(Integer, ForeignKey('parent.id'))
relationship
does not affect the database schema. It provides a convenient way to access related objects. In this instance it allows you to get all Child
objects that are related to a Parent
through the children
attribute. backref
then adds a parent
attribute to all Child
objects.
By default, related objects will be loaded through a SELECT
query. By passing lazy='joined'
to relationship
, however, the two tables will be joined when querying.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With