SQLAlchemy通过相关类构造关联数据

2024-04-19 14:50:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这个设计

# coding: utf-8
from sqlalchemy import Column, VARCHAR, ForeignKey, create_engine
from sqlalchemy.dialects.mysql import INTEGER, TINYINT
from sqlalchemy.orm import relationship, sessionmaker
from sqlalchemy.inspection import inspect
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.ext.associationproxy import association_proxy


engine = create_engine('mysql://root:toor@localhost/test', echo=True)
Model = declarative_base()
Session = sessionmaker(bind=engine)
session = Session()


class A(Model):
    __tablename__ = 'A'

    id = Column(INTEGER(unsigned=True), primary_key=True)
    name = Column(VARCHAR(32), nullable=False, index=True)


class AB(Model):
    __tablename__ = 'AB'

    A_id = Column(INTEGER(10, unsigned=True), ForeignKey('A.id'), nullable=False, primary_key=True)
    B_id = Column(INTEGER(10, unsigned=True), ForeignKey('B.id'), nullable=False, primary_key=True)
    type = Column(TINYINT(3, unsigned=True), nullable=False)
    A_rel = relationship(
    "A",
    foreign_keys=[A_id]
    )
    B_rel = relationship(
    "B",
    foreign_keys=[B_id],
    )


mapper_AB = inspect(AB)


class B(Model):
    __tablename__ = 'B'

    id = Column(INTEGER(10, unsigned=True), primary_key=True)

    As = relationship("A", secondary=mapper_AB.local_table, uselist=False)
    ABs = relationship("AB")
    type = association_proxy('ABs', 'type')


Model.metadata.create_all(engine)

a = A(
    name="test",
)

session.add(a)
session.commit()

b = B(
    As=a,
    type=2
)
print(b.type)

session.add(b)
session.commit()

这显然失败了,但我正试图通过一个(B)相关类构造函数添加AB额外信息(type)来简化设计。你知道吗

我已经阅读了大量的SQLAlchemy文档,甚至在源代码中迷失了自己,但都没有用。数据库的3表设计不能修改,因为它是更大系统的一部分,属于另一个项目。我的目标是将这些表映射到一个更简化的设计中,以便在将来的开发中使用这些模型。你知道吗

这是否可能使用声明式风格的SQLAlchemy机制?你知道吗


Tags: fromimportidfalsetruemodelabsqlalchemy