SQLAlchemy有附加列的条件多对多关系

时间:2019-01-11 08:50:54

标签: sqlalchemy many-to-many

这是我通常用于实现m2m关系的方式。 (摘自docs.sqlalchemy.org)

association_table = Table('association', Base.metadata,
    Column('left_id', Integer, ForeignKey('left.id')),
    Column('right_id', Integer, ForeignKey('right.id'))
)

class Parent(Base):
    __tablename__ = 'left'
    id = Column(Integer, primary_key=True)
    children = relationship("Child",
                    secondary=association_table,
                    backref="parents")

class Child(Base):
    __tablename__ = 'right'
    id = Column(Integer, primary_key=True)

有什么方法可以使用association_table表中的其他列?

所以应该像

association_table = Table('association', Base.metadata,
    Column('left_id', Integer, ForeignKey('left.id')),
    Column('right_id', Integer, ForeignKey('right.id')),
    Column('is_valid', Boolean, default=True)  # Add the validation column
)

class Parent(Base):
    __tablename__ = 'left'
    id = Column(Integer, primary_key=True)
    children = relationship("Child",
                    secondary=association_table,
                    backref="parents")

    # How can I do implement this??
    valid_children = relationship("Child",
                    secondary="and_(association_table.left_id == Parent.id, association_table.right_id == Child.id)"

class Child(Base):
    __tablename__ = 'right'
    id = Column(Integer, primary_key=True)

我要查询的内容取决于is_valid列。如何修改Parent表中的“辅助”属性?还是应该修复另一部分?

this question中,time_create列的所有子项都具有相同的值。但是在这种情况下,我需要一个标志,使该标志能够检索此连接是否仍然有效。

例如,如果您实现一对一聊天,将会有一个由两人组成的聊天室,对吧?
表格应如下所示:

association_table = Table('association', Base.metadata,
    Column('left_id', Integer, ForeignKey('left.id')),
    Column('right_id', Integer, ForeignKey('right.id')),
    Column('is_left', Boolean, default=False)  # Whether the user left or not
)

class Match(Base):
    __tablename__ = 'left'
    id = Column(Integer, primary_key=True)
    user = relationship("User",
                    secondary=association_table,
                    backref="matches")

    # How can I do implement this??
    exist_user = relationship("User",
                    secondary="and_(association_table.left_id == Parent.id, association_table.right_id == Child.id)"

class User(Base):
    __tablename__ = 'right'
    id = Column(Integer, primary_key=True)
    nickname = Column(String, unique=True)

我该怎么做?

0 个答案:

没有答案
相关问题