gpt4 book ai didi

python - 何时以及如何创建 sqlalchemy 链接表对象?

转载 作者:太空宇宙 更新时间:2023-11-04 05:45:52 25 4
gpt4 key购买 nike

当我在 sqlalchemy 中有多对多关系并且该链接表映射到一个类时,该 ORM 对象是如何以及何时创建的?例如,我无法通过 session.new 找到它。

这是一个简单的例子来解释它:

from sqlalchemy import create_engine
from sqlalchemy import Column, DateTime, String, Integer, ForeignKey, func
from sqlalchemy.orm import relationship
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker


Base = declarative_base()


class Department(Base):
__tablename__ = 'department'
id = Column(Integer, primary_key=True)
name = Column(String)
employees = relationship(
'Employee',
secondary='department_employee_link'
)


class Employee(Base):
__tablename__ = 'employee'
id = Column(Integer, primary_key=True)
name = Column(String)
hired_on = Column(DateTime, default=func.now())
departments = relationship(
Department,
secondary='department_employee_link'
)


class DepartmentEmployeeLink(Base):
__tablename__ = 'department_employee_link'
department_id = Column(Integer, ForeignKey('department.id'), primary_key=True)
employee_id = Column(Integer, ForeignKey('employee.id'), primary_key=True)


engine = create_engine('sqlite:///:memory:')
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)


session = Session()
department = Department(name='department')
employee = Employee(name='employee')
department.employees.append(employee)
session.add(department)

# When does DepartmentEmployeeLink get created if ever as an ORM object?
print session.new

谢谢!

最佳答案

除非您显式查询该表,否则不会创建 DepartmentEmployeeLink 的实例。对于插入和查询 EmployeeDepartment 实例,DepartmentEmployeeLink class 对象中的信息就足够了。无需为此创建实例。

关于python - 何时以及如何创建 sqlalchemy 链接表对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32331734/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com