这里有三种一般的方法。
一种是,做一个“香草”设置,你有“工作”/“工人”设置而不区分“类型” - 然后,使用relationship()
“作曲家”,“作曲家”,“翻译者”,“翻译”使用“次要”,Assignment.__table__
以及自定义连接条件,以及viewonly=True
. 因此,您只能通过 vanilla 属性进行写入。这里的一个缺点是“vanilla”和“specific”集合之间没有立即同步。
另一个是,与“vanilla”设置相同,但只使用普通的 Python 描述符在内存中给出“composer”、“composed”、“translator”、“translated”视图,即[obj.worker for obj in self.workers if obj.type == 'composer']
. 这是最简单的方法。无论您放入“vanilla”集合中的什么内容都会直接显示在“filtered”集合中,SQL 很简单,并且使用的 SELECT 语句更少(每个 Worker/Work 一个,而不是每个 Worker/Work 的 N 个)。
最后,最接近您所要求的方法,主要连接和反向引用,但请注意关联对象,反向引用在 Work/Assignment 和 Assignment/Worker 之间,而不是直接在 Work/Worker 之间。这种方法可能最终会使用更多的 SQL 来获得结果,但它是最完整的,并且还具有自动编写“类型”的漂亮特性。我们还使用了“单向反向引用”,因为 Assignment 没有一种简单的向外关联的方法(有办法做到这一点,但会很乏味)。使用 Python 函数自动创建关系会减少样板文件,注意这里我使用字符串作为“类型”,如果您向系统添加更多参数,这可以是一个整数:
from sqlalchemy import *
from sqlalchemy.orm import *
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.ext.associationproxy import association_proxy
Base = declarative_base()
def _work_assignment(name):
assign_ = relationship("Assignment",
primaryjoin="and_(Assignment.work_id==Work.id, "
"Assignment.type=='%s')" % name,
back_populates="work", cascade="all, delete-orphan")
assoc = association_proxy("%s_assign" % name, "worker",
creator=lambda worker: Assignment(worker=worker, type=name))
return assoc, assign_
def _worker_assignment(name):
assign_ = relationship("Assignment",
primaryjoin="and_(Assignment.worker_id==Worker.id, "
"Assignment.type=='%s')" % name,
back_populates="worker", cascade="all, delete-orphan")
assoc = association_proxy("%s_assign" % name, "work",
creator=lambda work: Assignment(work=work, type=name))
return assoc, assign_
class Work(Base):
__tablename__ = 'work'
id = Column(Integer, primary_key=True)
name = Column(String(50))
description = Column(Text)
composers, composer_assign = _work_assignment("composer")
translators, translator_assign = _work_assignment("translator")
class Worker(Base):
__tablename__ = 'worker'
id = Column(Integer, primary_key=True)
name = Column(String(50))
description = Column(Text)
composed, composer_assign = _worker_assignment("composer")
translated, translator_assign = _worker_assignment("translator")
class Assignment(Base):
__tablename__ = 'assignment'
work_id = Column(Integer, ForeignKey('work.id'), primary_key=True)
worker_id = Column(Integer, ForeignKey('worker.id'), primary_key=True)
type = Column(String, nullable=False)
worker = relationship("Worker")
work = relationship("Work")
e = create_engine("sqlite://", echo=True)
Base.metadata.create_all(e)
session = Session(e)
ww1, ww2, ww3 = Worker(name='Xueqin Cao'), Worker(name='Xianyi Yang'), Worker(name='Naidie Dai')
w1 = Work(name='A Dream of The Red Mansions')
w1.composers.append(ww1)
w1.translators.extend([ww2, ww3])
session.add(w1)
session.commit()
work = session.query(Work).get(1)
assert work.name == 'A Dream of The Red Mansions'
assert work.composers == [ww1]
assert work.translators == [ww2, ww3]
worker = session.query(Worker).get(ww1.id)
assert worker.name == 'Xueqin Cao'
assert worker.composed == [work]
assert worker.translated == []
worker.composed[:] = []
# either do this...
session.expire(work, ['composer_assign'])
# or this....basically need composer_assign to reload
# session.commit()
assert work.composers == []