Say I have a SqlAlchemy model something like this:
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'))
I'd like to have some kind of "relationship" from Employee directly to EmployeeType.name as a convenience, so I can skip the step of looking up an id or EmployeeType object if I have a type name:
emp = Employee()
emp.type_name = "drone"
session.add(emp)
session.commit()
assert (emp.type.id == 1)
Is such a thing possible?
EDIT: I found that association_proxy can get me partway there:
class Employee(Base):
...
type_name = association_proxy("type", "name")
the only problem being that if I assign to it:
emp = session.query(Employee).filter_by(EmployeeType.name=='PHB').first()
emp.type_name = 'drone'
it modifies the employee_type.name column, not the employee.type_id column.