SQLAlchemy 多对多
2021/7/26 2:12:07
本文主要是介绍SQLAlchemy 多对多,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
参考官网: https://www.pythoncentral.io/sqlalchemy-orm-examples/
员工部门两个表,中间为多对多关系,这种一般需要创建一个中间表。多对多转换成一对多
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) employees = relationship('Employee', secondary='department_employee') class Employee(Base): __tablename__ = 'employee' id = Column(Integer, primary_key=True) name = Column(String) departments = relationship('Department', secondary='department_employee') class DepartmentEmployee(Base): __tablename__ = 'department_employee' department_id = Column(Integer, ForeignKey('department.id'), primary_key=True) employee_id = Column(Integer, ForeignKey('employee.id'), primary_key=True) engine = create_engine("sqlite:///") session = sessionmaker() session.configure(bind=engine) Base.metadata.create_all(engine) s = session() john = Employee(name='Jhon') s.add(john) it_department = Department(name='IT') it_department.employees.append(john) s.add(it_department) s.commit() johnDB = s.query(Employee).filter(Employee.name == 'Jhon').one() print(johnDB.name) print(johnDB.departments[0].name)
这篇关于SQLAlchemy 多对多的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-11-27Excel中实现拖动排序的简单教程
- 2024-11-27Rocket消息队列资料:新手入门指南
- 2024-11-27rocket消息队资料详解与入门指南
- 2024-11-27RocketMQ底层原理资料详解入门教程
- 2024-11-27RocketMQ项目开发资料:新手入门教程
- 2024-11-27RocketMQ项目开发资料详解
- 2024-11-27RocketMQ消息中间件资料入门教程
- 2024-11-27初学者指南:深入了解RocketMQ源码资料
- 2024-11-27Rocket消息队列学习入门指南
- 2024-11-26Rocket消息中间件教程:新手入门详解