30

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?

1

2 Answers 2

37

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

7

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.

1
  • 8
    To be precise - it doesn't matter when they created the Location instance, it matters when/how they created the table in whatever SQL backend they are using. Even restarting the Python code (which would reload the db.Model) would not solve the problem unless the SQL tables themselves are being recreated. I'm not sure if this is what you meant, but the wording was a little ambiguous. Also, they don't NEED to use Alembic; what they NEED is to actually add the NOT NULL constraint to their SQL table.
    – dwanderson
    Mar 19, 2018 at 20:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.