From 9eafc1d73867ae38fe5be984368bd64f7f16aa68 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Fran=C3=A7oise=20Conil?= <francoise.conil@liris.cnrs.fr>
Date: Thu, 13 Jan 2022 17:27:44 +0100
Subject: [PATCH] =?UTF-8?q?Code=20compl=C3=A9t=C3=A9=20pour=20mieux=20visu?=
 =?UTF-8?q?aliser=20le=20r=C3=A9sultat=20(=5F=5Frepr=5F=5F)?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

---
 relationship/one_to_many.2.py | 26 ++++++++++++++++++++++++--
 1 file changed, 24 insertions(+), 2 deletions(-)

diff --git a/relationship/one_to_many.2.py b/relationship/one_to_many.2.py
index e9855e9..ff743e2 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)>
-- 
GitLab