简体   繁体   中英

SQLAlchemy optional ForeignKey

In SQLAlchemy.orm I have the following 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])

I want to make the src and source optional which means those records could be empty in the table. In Django's ORM, I used to make a model field optional by using blank=True and null=True like:

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

There is a default parameter for each column in SQLAlchemy as well. I tried:

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

But it doesn't work.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM