Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/314.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python SQLAlchemy可选外键_Python_Django_Database_Sqlalchemy - Fatal编程技术网

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
,这是默认值<代码>默认值=…
有完全不同的用途(有关详细信息,请参阅同一文档页。有关详细信息,请参阅。当您编写“它不起作用”时,是否可以更具体一些。@谢谢,这解决了我的问题!