How to use nullable field with non-null default #2003
Replies: 1 comment 1 reply
|
That default 1 isn't coming from Pydantic, it's a SQLAlchemy column default. To make unset give 1 but explicit None give NULL, move the default off the column so only the Pydantic side remains: from sqlalchemy import Column, Integer
field: int | None = Field(default=1, sa_column=Column(Integer, nullable=True))Keep |

That default 1 isn't coming from Pydantic, it's a SQLAlchemy column default.
Field(default=1)attaches aScalarElementColumnDefault(1)to the column, and a scalar column default gets applied on INSERT whenever the value is None, so your explicit None gets replaced with 1. There's no column default on UPDATE (that'sonupdate), which is why setting it to None and committing again keeps the null.To make unset give 1 but explicit None give NULL, move the default off the column so only the Pydantic side remains:
Keep
default=1on the Field, that's now what fills 1 when the att…