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

时间:2018-05-04 10:37:44

标签: python orm sqlalchemy associations

我有这个设计

# 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额外信息(类型)来简化设计。

我已经浏览了大量的SQLAlchemy文档,甚至在源代码中丢失了自己,但无济于事。数据库的3表设计无法修改,因为它是更大系统的一部分,属于另一个项目。我的目标是将这些表格映射到更简化的设计中,以便进一步开发这些模型。

这是否可以使用具有声明式样式的SQLAlchemy机制?

0 个答案:

没有答案