SQLAlchemy如何创建表的“类型”行与表模型或混合的关系或映射

时间:2019-03-15 14:06:51

标签: python orm sqlalchemy

当我将行持久保存到具有各种entity_types的通用表时,需要将entity_type_id设置为列值。我应该能够在实例化时为每个特定实例加载entity_type_id,因为可以通过简单的select语句访问它。我希望在类(或实例)级别自动检索/设置该ID,而无需执行查询和/或每次我持久保存一行“ entity_type”时都对其进行手动设置。

我在mixin上尝试了一个attribute_type_id @property,它使用object_session返回了object_type的ID,但由于某些原因,我不完全理解在提交/刷新会话时,orm仍会插入null作为object_type_id的值。 (我猜想拥有“属性”本身与在实例上设置属性值和/或引起问题是不一样的,因为基类中的列名称具有相同的名称)

这是我的架构中相关模型的精简版:

class EntityType(Base):
__tablename__ = 'entity_type'

id = Column(UUID(as_uuid=True), primary_key=True, server_default=FetchedValue())
table_name = Column(String, nullable=False)
ui_label = Column(Text, unique=True, nullable=False)
entry_key = Column(Text, unique=True, nullable=False)

基类模型:

class TrackedEntity(Base):

@declared_attr
def __tablename__(cls):
    return convert(cls.__name__)

__table_args__ = (
    UniqueConstraint('entity_type_id', 'label'),
)

id = Column(UUID(as_uuid=True), primary_key=True, server_default=FetchedValue())
entity_type_id = Column('entity_type_id', ForeignKey('entity_type.id'))
label = Column('label', String, nullable=False)

entity_type = relationship('EntityType')

polymorphic_discriminator = column_property(select([EntityType.table_name]).where(EntityType.id == entity_type_id).as_scalar())

@declared_attr
def entity_type_label(cls):
    return association_proxy('entity_type', 'label')

@declared_attr
def __mapper_args__(cls):
    if cls.__name__ == 'TrackedEntity':
        return {
            "polymorphic_on": cls.polymorphic_discriminator,
            "polymorphic_identity": cls.__tablename__
        }
    else:
        return {"polymorphic_identity": cls.__tablename__}

儿童课堂混合:

class TrackedEntityMixin(object):
        # noinspection PyMethodParameters

    @declared_attr
    def id(cls) -> Column:
        return Column(ForeignKey('tracked_entity.id'), primary_key=True)
    #gets me the id but isn't very helpful like this, still needs to be manually set like child.entity_type_id = child._entity_type_id
    @property
    def _entity_type_id(self):
        return object_session(self). \
            scalar(
            select([EntityType.id]).
                where(EntityType.table_name == self.__tablename__)
        )

子类模型:

class DesignedMolecule(TrackedEntityMixin, TrackedEntity):


      extra = Column('extra', String)
      parents = relationship('TrackedEntity', secondary='mix_dm_parent_entity')

0 个答案:

没有答案