How to insert NULL value in SQLAlchemy?

Question:

I’ve a Table with the following column:

Column('type', String(128))

How do I set this column to NULL when inserting a new row in database?

I tried doing this:

self.type = NULL;

There is no NULL type in Python so I don’t know how to do it.

Asked By: bodacydo

||

Answers:

Instead of trying

self.type = NULL

try as Yaroslav Admin suggested

self.type = None

As Python’s equivalent for NULL is None.

Answered By: Hayk Davtyan

I know this is an old thread but this worked for me

self.type = sqlalchemy.sql.null()
Answered By: omeanwell

As the other answers have pointed out, an explicit NULL can be inserted by passing None, or in case of SQLAlchemy a null() construct, as the value. In fact PEP-249 “DB-API v2.0” clearly states this in “Type Objects and Constructors”:

SQL NULL values are represented by the Python None singleton on input and output.

As a third option one can simply omit the column, if it is nullable:

t = Table('t', metadata,
          Column('a', Integer),
          Column('b', Integer))

stmt = t.insert().values(a=1)
engine.execute(stmt)

would effectively insert a new row (1, NULL) in the table t, because a value was not provided for column b. The same applies for mapped classes, which I suppose the original question is actually using (because of the self):

class T(Base):
    __tablename__ = 't'
    id = Column(Integer, primary_key=True)
    a = Column(Integer)
    b = Column(Integer)

session.add(T(a=1))
session.commit()

again effectively results in (default, 1, NULL) being inserted.

Answered By: Ilja Everilä
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.