python - How define reverse polymorphic in SQLAlchemy? -
tables
parents:
id | child_type | child_id --- | ---------- |-------- 1 | student | 5 7 | student | 8 9 | employee | 3 15 | employee | 8 29 | employee | 12 students:
id | name --- | ---------- 1 | jerry .. | ... 5 | alex 8 | tom employees:
id | name --- | ---------- 3 | john .. | ... 8 | mike 12 | susan files
models.py:
from sqlalchemy.ext.declarative import declarative_base, abstractconcretebase sqlalchemy.schema import column, foreignkey sqlalchemy.sql.sqltypes import integer, string base = declarative_base() class parent(base): __tablename__ = 'parents' id = column(integer, pirmary_key=true) child_type = column(string) child_id = column(integer) child = relationship('child', uselist=false) class child(abstractconcretebase, base): name = column(string) class student(child): __tablename__ = 'students' __mapper_args__ = { 'polymorphic_identity': 'student', 'concrete': true } id = column(integer, foreignkey(parent.child_id), primary_key=true) class employee(child): __tablename__ = 'employees' __mapper_args__ = { 'polymorphic_identity': 'employee', 'concrete': true } id = column(integer, foreignkey(parent.child_id), primary_key=true) main.py:
from sqlalchemy import create_engine sqlalchemy.orm import sessionmaker models import parent if __name__ == '__main__': engine = create_engine('mysql~~', encoding='utf-8') session = sessionmaker(bind=engine)() parent_success_1 = session.query(parent).get(1) # <parent(id=1, child_type='student', child_id=5)> assert parent_success_1.child.name == 'alex' # success parent_success_2 = session.query(parent).get(15) # <parent(id=15, child_type='employee', child_id=8)> assert parent_success_2.child.name == 'mike' # success parent_failure = session.query(parent).get(7) # <parent(id=7, child_type='student', child_id=8)> assert parent_failure.child.name == 'tom' # failed # sqlalchemy.orm.exc.multipleresultsfound: multiple rows found one() parent has child pointer via (child_type, child_id). want access child polymorphic set child_type, child_id.
but when use rails's belongs_to polymorphic style columns, can not load polymorphic instance parent.
if set uselist=true (default) in parent model like:
child = relationship('child') parent_failure.child returns:
[<student(id=8, name='tom')>, <employee(id=8, name='mike')>] how can set polymorphic_on parent's child_type column using it?
Comments
Post a Comment