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?
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.
The @Column(nullable = false) Annotation It's used mainly in the DDL schema metadata generation. This means that if we let Hibernate generate the database schema automatically, it applies the not null constraint to the particular database column.
Columns are nullable by default The default value of SQLAlchemy nullable is False unless it's a primary key. A foreign key is also nullable by default.
1 Answer. Show activity on this post. So for check = Column(Boolean, default=False, nullable=True) default will be set to False when no value is specified i.e, nullable=True, right? Since nullable=True allows column to be NULL.
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).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With