Relationship to different tables in SQLalchemy

痞子三分冷 提交于 2021-02-19 06:57:25

问题


I have multiple tables. All tables have multiple columns that could not logically be stored in one merged table.

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(...)

Now I want to save changes in a history table:

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, ...))

Now my problem is: How can I populate Diff.foreign_id in the same commit when inserting a new Foo, Bar, or Baz?

This works, but if there should be a problem to insert the Diff then it is too late to rollback the changes to 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 :-(')

For normal relationships the id is inserted automagically:

class FooDiff(Model):
    diff_id = Column(...)
    foo_id = Column(Integer(unsigned=True), ForeignKey(...), ...)
    foo = relationship(Foo)

But I don't have Diff.foo, because Diff.foreign_id could point to many different tables.


回答1:


The solution I came up with is almost the same as that what @van has linked: ORM Examples: Generic Associations.

def _foreign_id_rel(Cls):
    return relationship(
        Cls,
        uselist=False,
        lazy=False,  # This is just my use case, not needed
        primaryjoin=lambda: and_(
            Diff.foreign_table == Cls.__tablename__,
            foreign(Diff.foreign_id) == Cls.id,
        ),
        backref=backref(
            'diffs',
            uselist=True,
            lazy=True,  # This is just my use case, not needed
            primaryjoin=lambda: and_(
                Diff.foreign_table == Cls.__tablename__,
                foreign(Diff.foreign_id) == Cls.id,
            ),
        ),
    )


class Diff(Model):
    ...

    foo = _foreign_id_rel(Foo)
    bar = _foreign_id_rel(Bar)
    baz = _foreign_id_rel(Baz)

    @property
    def foreign(self):
        if self.foreign_table:
            return getattr(self, self.foreign_table)

    @foreign.setter
    def foreign(self, value):
        if value is None:
            self.foreign_table = None
            self.foreign_id = None
        else:
            tbl_name = value.__tablename__
            self.foreign_table = tbl_name
            setattr(self, tbl_name, value)


来源:https://stackoverflow.com/questions/32570645/relationship-to-different-tables-in-sqlalchemy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!