Repository navigation
Replies: 1 comment
|
There are three separate issues in this example:
For that nullable-value example, the two conversion points can be expressed like this: from pydantic import field_validator
from sqlalchemy import Column, Integer
from sqlalchemy.types import TypeDecorator
from sqlmodel import Field, SQLModel
def zero_as_none(value: int | None) -> int | None:
return None if value == 0 else value
class ZeroAsNullInteger(TypeDecorator):
impl = Integer
cache_ok = True
def process_bind_param(self, value, dialect):
return zero_as_none(value)
def process_result_value(self, value, dialect):
return zero_as_none(value)
class MyModel(SQLModel, table=True):
id: int | None = Field(default=None, primary_key=True)
x: int | None = Field(
default=None,
sa_column=Column(ZeroAsNullInteger(), nullable=True),
)
@field_validator("x", mode="after")
@classmethod
def normalize_x(cls, value: int | None) -> int | None:
return zero_as_none(value)
m = MyModel.model_validate({"x": 0})
assert m.x is NoneThe Pydantic validator normalizes validated input in memory. The SQLAlchemy bind hook normalizes values sent to the database, and the result hook also normalizes a stored zero when reading it. The latter hooks are database I/O hooks, so they do not rewrite an attribute immediately when you call After inserting this revised model, check References: Pydantic field validators, SQLAlchemy TypeDecorator bind/result hooks, and SQLModel's generated-ID explanation. |
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
First Check
Commit to Help
Example Code
Description
When I look at this code, it seems straight-forward. The linters and type checkers complain about assigning
Nonetoxbut more importantly,assert m.x is Nonefails.This is a silly example: an
intfield that isNoneinstead of 0 and otherwise just anint, but I am wondering how to get there.How would you do it?
Operating System
Linux, Windows, macOS, Other
Operating System Details
No response
SQLModel Version
0.0.24
Python Version
3.13.3
Additional Context
No response
All reactions