I\'ve a Table
with the following column:
Column(\'type\', String(128))
How do I set this column to NULL when inserting a new r
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.