`nullable = False`在SQLAlchemy中如何工作 [英] How does `nullable=False` work in SQLAlchemy

查看:520
本文介绍了`nullable = False`在SQLAlchemy中如何工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

来自SQLAlchemy文档:

From SQLAlchemy docs:

nullable –如果设置为默认值True,则表示该列为 呈现为允许NULL,否则呈现为NOT NULL.这 参数仅在发出CREATE TABLE语句时使用.

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基本上使该列成为必需.例如:

I thought setting nullable=True for a Column basically made that Column required. For example:

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

但是,当我创建一个没有纬度字段的Location实例时,不会出现错误!

However, when I create a Location instance without a latitude field, I do not get an error!

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>

这是怎么回事?

推荐答案

您参考的文档解释了该问题:

The doc you reference explains the issue:

仅在发出CREATE TABLE语句时使用此参数.

This parameter is only used when issuing CREATE TABLE statements.

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

If you originally created your database without nullable=False (or created it in some other way, separate from SQLAlchemy, without NOT NULL on that column), then your database column doesn't have that constraint information. This information lives in reference to the database column, not to a particular instance you are creating/inserting.

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

Changing the SQLAlchemy table creation, without rebuilding your tables, means changes will not be reflected. As a link in a comment explains, SQLAlchemy is not doing the validation at that level (you would need to use the @validates decorator or some other such thing).

这篇关于`nullable = False`在SQLAlchemy中如何工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆