Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the relationship() function used for in SQLAlchemy

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'))
like image 660
Darc Nawg Avatar asked Dec 08 '22 05:12

Darc Nawg


1 Answers

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.

like image 143
dirn Avatar answered Dec 21 '22 04:12

dirn