How to insert NULL value in SQLAlchemy?

后端 未结 3 898
离开以前
离开以前 2020-12-11 14:54

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

3条回答
  •  感情败类
    2020-12-11 15:21

    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.

提交回复
热议问题