16

I have the following column in SQLAlchemy:

name = Column(String(32), nullable=False)

I want that if no value is passed onto an insertion, it should enter a default value of either completely blank or if not possible, then default as NULL.

Should I define the column as :

name = Column(String(32), nullable=False, default=NULL)

Because in python NULL object is actually None

Any suggestions?

1
  • 2
    If your column is not nullable, then you cannot have default=None. You can have a placeholder string (default='' for example). If you want to have database NULL there, then you need to define the field as nullable=True. Commented Mar 22, 2018 at 12:51

2 Answers 2

26

If you want an empty string as default, you can:

name = Column(String(32), nullable=False, default='')

However, if you just do:

name = Column(String(32), nullable=True)

then the default value of the column will be a NULL.

Note that a NULL value indicates “unknown value”, and typically should not be confused with an empty string. If your application needs the concept of “unknown value”, then make your column nullable. If not, make it non-nullable and default to empty strings.

Sign up to request clarification or add additional context in comments.

1 Comment

Although it doesn’t seem to be documented, nullable String colums actually default to an empty string. This can cause trouble e.g. in MySQL where a nullable field with a unique index allows multiple NULL values, but doesn’t allow multiple empty strings.
0

If you want exactly default NULL in your SQL, you may define the column as follow:

name = Column(String(32),
              server_default=sqlalchemy.sql.elements.TextClause('NULL'))

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.