当我在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
谢谢!
答案 0 :(得分:1)
除非您明确查询该表,否则不会创建DepartmentEmployeeLink
的实例。要插入和查询Employee
或Department
个实例,DepartmentEmployeeLink
类对象中的信息就足够了。没有必要为此创建实例。