“nullable=False”如何在SQLAlchemy中工作

2024-10-06 14:29:13 发布

您现在位置:Python中文网/ 问答频道 /正文

来自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.

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

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>

怎么回事?


Tags: the文档truedefaultdbifsqlalchemyas
2条回答

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

This parameter is only used when issuing CREATE TABLE statements.

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

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

首次创建位置实例并将其提交到数据库时,“nullable”是否设置为True?如果是,sqlalchemy将不允许您随后将可空参数重置为“False”。必须使用Alembic迁移数据库

相关问题 更多 >