How does `nullable=False` work in SQLAlchemy

Question:

From SQLAlchemy docs:

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.

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)
    ...

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>

What is going on?

Asked By: Ben Sandler

||

Answers:

when you first created a Location instance and committed it to the database, was ‘nullable’ set to True? if so, sqlalchemy will NOT allow you to subsequently reset the nullable parameter to ‘False’. You would have to migrate your database using Alembic

Answered By: Mark Pham

The doc you reference explains the issue:

This parameter is only used when issuing CREATE TABLE statements.

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.

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).

Answered By: dwanderson