Python – SQLAlchethe and empty columns

database-designpythonsqlalchemy

When I try to insert a new record into the database using SQLAlchemy and I don't fill out all values, it tries to insert them as "None" (instead of omitting them). It then complains about "can't be null" errors. Is there a way to have it just omit columns from the sql query if I also omitted them when declaring the instance?

Best Solution

To add to the answer from Ali A, this means you need to have nullable=True in your column definition, so that NULL is allowed in the column. For example:

email_address = Column(String, nullable=True)

SQLAlchemy docs for Tables and Columns, excerpt from v1.2 doc:

nullable – When set to False, will cause the “NOT NULL” phrase to be added when generating DDL for the column. When True, will normally generate nothing (in SQL this defaults to “NULL”), except in some very specific backend-specific edge cases where “NULL” may render explicitly. Defaults to True unless primary_key is also True, in which case it defaults to False. This parameter is only used when issuing CREATE TABLE statements.