1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
| from datetime import date import sqlalchemy from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, Integer, String, DATE, ForeignKey from sqlalchemy.orm import sessionmaker, relationship from sqlalchemy import func
engine = create_engine("mysql+pymysql://root:root@localhost:3306/sqlalchemy-tutorial", encoding="utf-8", echo=False)
Base = declarative_base()
class Student(Base): __tablename__ = "student" id = Column(Integer, primary_key=True) name = Column(String(32), nullable=False) register_date = Column(DATE, nullable=False)
def __repr__(self): return "<%s name: %s >" % (self.id, self.name)
class StudyRecord(Base): __tablename__ = "study_record" id = Column(Integer, primary_key=True) day = Column(Integer, nullable=False) status = Column(String(32), nullable=False) stu_id = Column(Integer, ForeignKey("student.id"))
student = relationship("Student", backref="study_record")
def __repr__(self): return "<%id day: %s, status: %s >" % (self.id, self.day, self.status)
Base.metadata.create_all(engine)
SessionClass = sessionmaker(bind=engine) session = SessionClass()
student = Student(name="babb", register_date=date.today()) study_record = StudyRecord(day=10, status="Good", student=student)
session.add(student) session.add(study_record)
session.commit()
study_record = session.query(Student).filter( Student.name == "babb").first().study_record print(study_record)
student = session.query(StudyRecord).first().student print(student)
|