The following example has a sqlalchemy model module:
meta = MetaData(naming_convention={
"ix": 'ix_%(column_0_label)s',
"uq": "uq_%(table_name)s_%(column_0_name)s",
"ck": "ck_%(table_name)s_%(constraint_name)s",
"fk": "fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s",
"pk": "pk_%(table_name)s"
})
class Base(object):
"Modify base to add standard columns across tables"
@declared_attr
def __tablename__(cls):
return cls.__name__
id = Column(Integer, primary_key=True)
date = Column(DateTime, default=datetime.utcnow())
class MixinLabel(object):
label = Column(String, nullable=False)
Base = declarative_base(metadata=meta, cls=Base)
class Block(Base, MixinLabel):
descendantId = Column(Integer, ForeignKey('BlockGroup.id'))
groupId = Column(Integer, ForeignKey('BlockGroup.id'))
position = Column(Integer)
_descendant = relationship('BlockGroup',
cascade='all, delete-orphan',
single_parent=True,
foreign_keys=[descendantId],
backref=backref('_ascendant', uselist=False)
)
class BlockGroup(Base):
"Abstract class"
type = Column(String)
__mapper_args__ = {
'polymorphic_identity': 'blockgroup',
'polymorphic_on': type
}
children = relationship('Block',
cascade='all, delete-orphan',
backref=backref('group', uselist=False),
foreign_keys=[Block.groupId],
order_by='Block.position'
)
configure_mappers()
Pay attention to the call configure_mappers()at the end. This does not work. If I try to access the relation Block.group, I get an exception AttributeError:
AttributeError: 'Block' object has no attribute 'group'
According to this SO question , configure_mappers()should solve this problem. One way or another, configure_mappers()does not do its job. Something is wrong.
source
share