Untitled
unknown
plain_text
a year ago
1.4 kB
4
Indexable
Never
from sqlalchemy import Column, String, Integer, create_engine, ForeignKey from sqlalchemy.orm import sessionmaker, declarative_base, relationship, backref # => Configure --------------------------------------- engine = create_engine("sqlite:///base.db", echo=False) BaseModel = declarative_base() Session = sessionmaker(bind=engine) session = Session() class Person(BaseModel): __tablename__ = "peoples" pid = Column(Integer, primary_key=True, autoincrement=True) name = Column(String(10)) def __init__(self, name): self.name = name def __repr__(self): return f"<'{type(self).__name__}' {self.name}>" class Thing(BaseModel): __tablename__ = "things" thingid = Column(Integer, primary_key=True, autoincrement=True) name = Column(String(20)) person_id = Column(Integer, ForeignKey("peoples.pid")) person = relationship("Person", backref=backref("things")) def __init__(self, name, person): self.name = name self.person = person def __repr__(self): return f"{self.name} owned by {self.person.name}" p1 = Person(name="Mike") p2 = Person(name="Donlad") p3 = Person(name="Anna") t1 = Thing(name="A Phone", person=p1) t2 = Thing(name="A Book", person=p2) t3 = Thing(name="A Car", person=p3) results = session.query(Thing).all() for r in results: print(r)