【问题标题】:SQLAlchemy optional ForeignKeySQLAlchemy 可选 ForeignKey
【发布时间】:2021-08-16 06:43:56
【问题描述】:

在SQLAlchemy.orm我有以下课程:

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

我想将src 和source 设为可选,这意味着这些记录在表中可能为空。在 Django 的 ORM 中,我曾经使用 blank=True 和 null=True 使模型字段可选:

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

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

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

但它不起作用。

【问题讨论】:

  • Django ORM 中的 null=True 等价于 SQLAlchemy 中的 nullable=True,这是默认值。 default=... 的用途完全不同(有关更多信息,请参阅同一文档页面。有关更多信息,请参阅 Column.nullable。 当您写“它不起作用”时 - 您能否更具体一点。
  • @van 谢谢,这解决了我的问题!

标签: python django database sqlalchemy


【解决方案1】:

按照@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)

【讨论】:

    猜你喜欢
    • 2015-08-08
    • 1970-01-01
    • 2011-11-25
    • 1970-01-01
    • 2015-06-29
    • 2021-08-10
    • 1970-01-01
    • 2020-11-22
    • 1970-01-01
    相关资源
    最近更新 更多