The Python Oracle

How does `nullable=False` work in SQLAlchemy

This video explains
How does `nullable=False` work in SQLAlchemy

--

Become part of the top 3% of the developers by applying to Toptal
https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Ancient Construction

--

Chapters
00:00 Question
01:01 Accepted answer (Score 33)
02:03 Answer 2 (Score 7)
02:29 Thank you

--

Full question
https://stackoverflow.com/questions/3319...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #sqlalchemy #flasksqlalchemy

#avk47



ACCEPTED ANSWER

Score 40


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




ANSWER 2

Score 8


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.