diff --git a/relationship/one_to_many.2.py b/relationship/one_to_many.2.py index e9855e96464d5976e2950bc53a890c310143d5e6..ff743e21d346236b12d4e9bb4f0a06321fae5d6a 100644 --- a/relationship/one_to_many.2.py +++ b/relationship/one_to_many.2.py @@ -6,7 +6,7 @@ many to one, specify an additional relationship() and connect the two using the relationship.back_populates parameter. """ from sqlalchemy import create_engine -from sqlalchemy import Column, ForeignKey, Integer +from sqlalchemy import Column, ForeignKey, Integer, String from sqlalchemy.orm import declarative_base, relationship from sqlalchemy.orm.session import Session @@ -17,17 +17,25 @@ class Parent(Base): __tablename__ = "parent" id = Column(Integer, primary_key=True) + name = Column(String) children = relationship("Child", back_populates="parent") + def __repr__(self): + return f"<Parent (name={self.name}, children={self.children})>" + class Child(Base): __tablename__ = "child" id = Column(Integer, primary_key=True) + name = Column(String) parent_id = Column(Integer, ForeignKey("parent.id")) parent = relationship("Parent", back_populates="children") + def __repr__(self): + return f"<Child (name={self.name})>" + if __name__ == "__main__": engine = create_engine("sqlite:///one_to_many.2.db", echo=False) @@ -37,5 +45,19 @@ if __name__ == "__main__": # cf ../basic-session.1.4.py with Session(engine) as session: + jack = Parent(name="Jack") + + alice = Child(name="Alice") + john = Child(name="John") + + jack.children = [john, alice] + with session.begin(): - pass + session.add(jack) + session.add(john) + session.add(alice) + + print(jack) + # <Parent (name=Jack, children=[<Child (name=John)>, <Child (name=Alice)>])> + print(alice) + # <Child (name=Alice)>