[Answered ]-SQLAlchemy optional ForeignKey

1👍

As suggested by @van, putting nullable=True in the ForeignKey not the relationship solved my problem:

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])

creating new instance:

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

Leave a comment