Combining table fields into a single model field #1632
First Check
Commit to Help
Example Codefrom pydantic import computed_field
from sqlmodel import SQLModel
class Foo(SQLModel, table=True):
field1: int
field2: int
field3: int
@computed_field
@property
def fields(self) -> list[int]:
return [self.field1, self.field2, self.field3]DescriptionThe database I am dealing with is really badly designed, and I would like to hide some of the atrocities in my models. Take the above example… is it possible to somehow make that model read the I am aware that I can use Pydantic to hide these fields from Operating SystemLinux Operating System DetailsDebian unstable SQLModel Version0.0.27 Python Version3.13.7 Additional ContextNo response |
Replies: 1 comment 1 reply
|
You can get most of the way there with from sqlalchemy import Column, Integer
from sqlmodel import SQLModel, Field
from pydantic import computed_field
class Foo(SQLModel, table=True):
field1_: int = Field(sa_column=Column("field1", Integer))
field2_: int = Field(sa_column=Column("field2", Integer))
field3_: int = Field(sa_column=Column("field3", Integer))
@computed_field
@property
def fields(self) -> list[int]:
return [self.field1_, self.field2_, self.field3_]
The part that's worth being upfront about: there's no way to make If you want the raw columns to be fully absent from what callers/IDEs see, the usual way out is a layer of indirection: keep the table model private to your data-access code (only that module ever imports it), and expose a separate plain (non- |
You can get most of the way there with
sa_columnto decouple the Python attribute name from the DB column name, pluscomputed_fieldfor the derived accessor:sa_column=Column("field1", ...)maps the attribute to the real (ugly) column n…