• 周六. 10月 8th, 2022

5G编程聚合网

5G时代下一个聚合的编程学习网

热门标签

SQLAlchemy 一对多

admin

11月 28, 2021

照着官网:https://www.pythoncentral.io/sqlalchemy-orm-examples/ 敲了一遍

创建两个表,一个Employ员工表,一个Department表,一个部门有多个员工,一个员工只能属于一个部门。一对多的关系

from sqlalchemy import Integer, Column, String, ForeignKey
from sqlalchemy.orm import declarative_base, relationship, backref, sessionmaker
from sqlalchemy import create_engine

Base = declarative_base()


class Department(Base):
    __tablename__ = 'department'
    id = Column(Integer, primary_key=True)
    name = Column(String)


class Employee(Base):
    __tablename__ = 'employee'
    id = Column(Integer, primary_key=True)
    name = Column(String)
    department_id = Column(Integer, ForeignKey('department.id'))
    department = relationship(Department, backref=backref('employees', uselist=True))


engine = create_engine("sqlite:///")
session = sessionmaker()
session.configure(bind=engine)
Base.metadata.create_all(engine)

john = Employee(name='Jhon')
it_department = Department(name='IT')
john.department = it_department
s = session()
s.add(john)
s.add(it_department)
s.commit()
it = s.query(Department).filter(Department.name == 'IT').one()
print(it.employees)
print(it.employees[0].name)
Please call me JiangYouDang!

发表回复

您的电子邮箱地址不会被公开。