gpt4 book ai didi

python - `nullable=False` 在 SQLAlchemy 中如何工作

转载 作者:太空狗 更新时间:2023-10-29 20:51:33 26 4
gpt4 key购买 nike

来自 SQLAlchemy 文档:

nullable – If set to the default of True, indicates the column will be rendered as allowing NULL, else it’s rendered as NOT NULL. This parameter is only used when issuing CREATE TABLE statements.

我认为为 Column 设置 nullable=True 基本上使该 Column 成为必需的。例如:

class Location(db.Model):
__tablename__ = 'locations'
id = db.Column(db.Integer, primary_key=True)
latitude = db.Column(db.String(50), nullable=False)
...

但是,当我创建一个没有纬度字段的 Location 实例时,我没有收到错误!

Python 2.7.8 (default, Oct 19 2014, 16:02:00)
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.54)] on darwin
Type "help", "copyright", "credits" or "license" for more information.

>>> Location(latitude=None)
<app.models.Location object at 0x10dce9dd0>

这是怎么回事?

最佳答案

您引用的文档解释了这个问题:

This parameter is only used when issuing CREATE TABLE statements.

如果您最初创建数据库时没有使用 nullable=False(或者以其他方式创建它,与 SQLAlchemy 分开,并且在该列上没有使用 NOT NULL),那么您的数据库 没有该约束信息。此信息存在于数据库列的引用中,而不是您正在创建/插入的特定实例。

在不重建表的情况下更改 SQLAlchemy 表的创建,意味着更改不会反射(reflect)出来。正如评论中的链接所解释的那样,SQLAlchemy 没有在该级别进行验证(您需要使用 @validates 装饰器或其他类似的东西)。

关于python - `nullable=False` 在 SQLAlchemy 中如何工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33192062/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com