26
votes

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.

3

3 Answers

47
votes

Instead of trying

self.type = NULL

try as Yaroslav Admin suggested

self.type = None

As Python's equivalent for NULL is None.

21
votes

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

self.type = sqlalchemy.sql.null()
6
votes

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.