Skip to content
Snippets Groups Projects
Commit 9eafc1d7 authored by Françoise Conil's avatar Françoise Conil
Browse files

Code complété pour mieux visualiser le résultat (__repr__)

parent 7412d818
No related branches found
No related tags found
No related merge requests found
......@@ -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)>
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment