39

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.

0

4 Answers 4

56

Instead of trying

self.type = NULL

try as Yaroslav Admin suggested

self.type = None

As Python's equivalent for NULL is None.

Sign up to request clarification or add additional context in comments.

1 Comment

This actually insert "null" in the column. If you want your field to be actually nothing, use sqlalchemy's null(). Check Ilja Everilä 's answer for more details
37

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

self.type = sqlalchemy.sql.null()

2 Comments

for me it's also available as simply sqlalchemy.null() (v1.2.5)
This is useful if you have a JSONB column because there is a difference between sqlalchemy.sql.null() - which is treated as SQL NULL - and None which is treated as JSON "null" which is not the same thing.
11

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.

Comments

0

You can declare:

Column('type', String(128), default=None)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.