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?

sshussain270
  • 1,785
  • 4
  • 25
  • 49
  • 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. – Hannu Mar 22 '18 at 12:51

2 Answers2

24

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.

tzot
  • 92,761
  • 29
  • 141
  • 204
  • 7
    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. – GergelyPolonkai Feb 07 '19 at 20:08
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'))
socrates
  • 1,203
  • 11
  • 16