尽管configure_mappers

时间:2017-10-21 13:55:04

标签: python sqlalchemy

在以下示例中,有一个sqlalchemy模型模块:

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)

    # one-to-one
    _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
    }

    # one-to-many
    children = relationship('Block',
                            cascade='all, delete-orphan',
                            backref=backref('group', uselist=False),
                            foreign_keys=[Block.groupId],
                            order_by='Block.position'
                            )
configure_mappers()

请注意最后的configure_mappers()来电。那个不起作用。如果我尝试访问Block.group关系,我会收到AttributeError异常:

AttributeError: 'Block' object has no attribute 'group'

根据this SO questionconfigure_mappers()应解决此问题。不知何故,configure_mappers()没有做好自己的工作。出了点问题。

0 个答案:

没有答案