假设我有一个类似于以下的SqlAlchemy模型:
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, String, Integer, ForeignKey
from sqlalchemy.orm import sessionmaker, relationship
Base = declarative_base()
Session = sessionmaker()
class EmployeeType(Base):
__tablename__ = 'employee_type'
id = Column(Integer(), primary_key=True)
name = Column(String(20))
class Employee(Base):
__tablename__ = 'employee'
id = Column(Integer(), primary_key=True)
type_id = Column(Integer(), ForeignKey(EmployeeType.id))
type = relationship(EmployeeType, uselist=False)
session = Session()
session.add(EmployeeType(name='drone'))
session.add(EmployeeType(name='PHB'))
我希望能够直接从员工到员工类型(EmployeeType.name)建立某种“关系”,以便我可以跳过查找ID或EmployeeType对象的步骤,更加方便:
emp = Employee()
emp.type_name = "drone"
session.add(emp)
session.commit()
assert (emp.type.id == 1)
这种事情可能吗?
编辑:我发现association_proxy可以帮助我实现部分功能:
class Employee(Base):
...
type_name = association_proxy("type", "name")
唯一的问题是,如果我给它分配:
emp = session.query(Employee).filter_by(EmployeeType.name=='PHB').first()
emp.type_name = 'drone'
它修改的是employee_type.name列,而不是employee.type_id列。