SQLAlchemy 可选外键

SQLAlchemy optional ForeignKey

SQLAlchemy.orm 我有以下 class:

class Table(Base):
    __tablename__ = 'table'

    id = Column(Integer, primary_key=True)

    src = Column(Integer, ForeignKey('other.id'))
    dst = Column(Integer, ForeignKey('other.id'))

    source = relationship("Other", foreign_keys=[src])
    destination = relationship("Other", foreign_keys=[dst])

我想将 srcsource 设为可选,这意味着 table 中的这些记录可能为空。在 Django 的 ORM 中,我曾经使用 blank=Truenull=True 使模型字段可选,例如:

src = models.ForeignKey(Other, blank=True, null=True)

SQLAlchemy 中的每一列也有一个 default 参数。我试过了:

src = Column(Integer, ForeignKey('other.id'), default=None)

但是没用。

按照@van 的建议,将 nullable=True 放在 ForeignKey 而不是 relationship 中解决了我的问题:

class Table(Base):
    __tablename__ = 'table'

    id = Column(Integer, primary_key=True)

    src = Column(Integer, ForeignKey('other.id'), nullable=True)
    dst = Column(Integer, ForeignKey('other.id'))

    source = relationship("Other", foreign_keys=[src])
    destination = relationship("Other", foreign_keys=[dst])

创建新实例:

instance = Table(src=None, dst=other)