Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explicitly set value of column to NULL when there is a default set on the Column in SqlAlchemy

I have a table defined like:

class Thing(Base):
    __tablename__ = "things"

    my_field = Column(Text, nullable=True, default=lambda c: "default")

(In my actual implementation the default function is more complicated, but I thought it pertinent to say I'm using a function to generate the default value.)

I would like to be able to explicitly set the value of my_field to NULL in some cases. I have tried:

thing = Thing(my_field=None)

But upon the Session.add(thing); Session.commit() the default value is generated by the function and writes over my explicit None. Is there a way to use the default in general but occasionally explicitly set Null for the column?

like image 574
Alex Avatar asked Oct 22 '25 04:10

Alex


1 Answers

This is due to a quirk in the SQLAlchemy ORM. Even if you explicitly set the value to None on a column with a default, it is treated as if no value was set. You need to use the null SQL construct in order to work around this issue. See Forcing NULL on a column with a default for more detail.

from sqlalchemy import null

thing = Thing(my_field=null())
like image 144
benvc Avatar answered Oct 23 '25 20:10

benvc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!