【发布时间】:2015-12-10 19:11:37
【问题描述】:
我有多个表。所有表都有多个列,这些列在逻辑上无法存储在一个合并表中。
class Foo(Model):
foo_id = Column(Integer(unsigned=True), primary_key=True, nullable=False)
foo_data = Column(...)
class Bar(Model):
bar_id = Column(Integer(unsigned=True), primary_key=True, nullable=False)
bar_info = Column(...)
class Baz(Model):
baz_id = Column(Integer(unsigned=True), primary_key=True, nullable=False)
baz_content = Column(...)
现在我想在历史表中保存更改:
class Diff(Model):
diff_id = Column(...)
foreign_id = Column(Integer(unsigned=True), index=True, nullable=False)
foreign_table = Column(Char(16, collation='ascii_bin'), index=True, nullable=False)
class SingleDiff(Model):
...
diff = relationship(Diff, backref=backref('changes', uselist=True, ...))
现在我的问题是:如何在插入新的Foo、Bar 或Baz 时在同一个提交中填充Diff.foreign_id?
这可行,但如果插入Diff 时出现问题,那么将更改回滚到foo 为时已晚:
foo = Foo(foo_data='TODO: changes table names')
try:
session.add(foo)
session.commit() # first commit
except ...:
....
else:
try:
diff = Diff(changes=[...])
diff.foreign_id = foo.foo_id
diff.foerein_table = 'foo'
session.add(diff)
session.commit() # second commit
except ...:
raise Exception('Cannot rollback commit #1 anymore :-(')
对于正常的关系,id 会自动插入:
class FooDiff(Model):
diff_id = Column(...)
foo_id = Column(Integer(unsigned=True), ForeignKey(...), ...)
foo = relationship(Foo)
但我没有Diff.foo,因为Diff.foreign_id 可以指向许多不同的表。
【问题讨论】:
-
阅读文档的Generic Associations 部分。我认为尤其是Generic Foreign Key 示例应该适合您的情况。
-
@van,谢谢你的链接!
标签: python sqlalchemy foreign-keys one-to-many