Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLAlchemy and empty columns

Tags:

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?

like image 936
ryeguy Avatar asked Feb 14 '09 11:02

ryeguy


People also ask

Are SQLAlchemy columns nullable by default?

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.

What is nullable in flask SQLAlchemy?

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.


1 Answers

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.

like image 66
Van Gale Avatar answered Oct 06 '22 16:10

Van Gale