python SQLAlchemy 和空列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/548952/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 20:21:15  来源:igfitidea点击:

SQLAlchemy and empty columns

pythondatabase-designsqlalchemy

提问by ryeguy

When I try to insert a new record into the database using SQLAlchemy and I don't fill out all values, it tries to insert them as "None" (instead of omitting them). It then complains about "can't be null" errors. Is there a way to have it just omit columns from the sql query if I also omitted them when declaring the instance?

当我尝试使用 SQLAlchemy 将新记录插入数据库并且我没有填写所有值时,它会尝试将它们插入为“无”(而不是省略它们)。然后它会抱怨“不能为空”错误。如果我在声明实例时也省略了列,有没有办法让它从 sql 查询中省略列?

采纳答案by Ali Afshar

This is a database schema issue, not an SQLAlchemy issue. If your database schema has a column which cannot be NULL, you must put something (i.e. not None) into there. Or change your schema to allow NULL in those columns.

这是一个数据库架构问题,而不是 SQLAlchemy 问题。如果你的数据库模式有一个不能为 NULL 的列,你必须在那里放一些东西(即不是 None)。或者更改您的架构以在这些列中允许 NULL。

Wikipedia has an article about NULLand an article which describes non-NULL constraints

维基百科有一篇关于 NULL的文章和一篇描述非 NULL 约束的文章

回答by Van Gale

To add to the answer from Ali A, this means you need to have nullable=Truein your column definition, so that NULL is allowed in the column. For example:

要添加到 Ali A 的答案,这意味着您需要nullable=True在列定义中有,以便列中允许 NULL。例如:

email_address = Column(String, nullable=True)

SQLAlchemy docs for Tables and Columns, excerpt from v1.2 doc:

表和列的 SQLAlchemy 文档,摘自 v1.2 文档:

nullable – When set to False, will cause the “NOT NULL” phrase to be added when generating DDL for the column. When True, will normally generate nothing (in SQL this defaults to “NULL”), except in some very specific backend-specific edge cases where “NULL” may render explicitly. Defaults to True unless primary_key is also True, in which case it defaults to False. This parameter is only used when issuing CREATE TABLE statements.

nullable – 当设置为 False 时,将导致在为列生成 DDL 时添加“NOT NULL”短语。当为 True 时,通常不会生成任何内容(在 SQL 中,这默认为“NULL”),除非在某些非常特定的后端特定边缘情况下,其中“NULL”可能会显式呈现。默认为 True 除非 primary_key 也是 True,在这种情况下它默认为 False。此参数仅在发出 CREATE TABLE 语句时使用。