Python SQLAlchemy可选外键
在Python SQLAlchemy可选外键,python,django,database,sqlalchemy,Python,Django,Database,Sqlalchemy,在SQLAlchemy.orm中,我有以下类: 类表(基本): __tablename_uu='table' id=列(整数,主键=True) src=列(整数,ForeignKey('other.id')) dst=列(整数,ForeignKey('other.id')) source=关系(“其他”,外键=[src]) 目的地=关系(“其他”,外键=[dst]) 我想将src和source设置为可选,这意味着表中的记录可能为空。在Django的ORM中,我使用blank=True和null
SQLAlchemy.orm
中,我有以下类:
类表(基本):
__tablename_uu='table'
id=列(整数,主键=True)
src=列(整数,ForeignKey('other.id'))
dst=列(整数,ForeignKey('other.id'))
source=关系(“其他”,外键=[src])
目的地=关系(“其他”,外键=[dst])
我想将src
和source
设置为可选,这意味着表中的记录可能为空。在Django的ORM中,我使用blank=True
和null=True
使模型字段成为可选字段,如:
src=models.ForeignKey(其他,blank=True,null=True)
SQLAlchemy
中的每一列都有一个default
参数。我试过:
src=Column(整数,ForeignKey('other.id'),默认值=None)
但是它不起作用。正如@van所建议的,将
nullable=True
放在ForeignKey
中而不是关系中解决了我的问题:
类表(基本):
__tablename_uu='table'
id=列(整数,主键=True)
src=Column(整数,ForeignKey('other.id'),nullable=True)
dst=列(整数,ForeignKey('other.id'))
source=关系(“其他”,外键=[src])
目的地=关系(“其他”,外键=[dst])
正在创建新实例:
instance=Table(src=None,dst=other)
Django ORM中的null=True
相当于SQLAlchemy中的null=True
,这是默认值<代码>默认值=…
有完全不同的用途(有关详细信息,请参阅同一文档页。有关详细信息,请参阅。当您编写“它不起作用”时,是否可以更具体一些。@谢谢,这解决了我的问题!