【发布时间】: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