Combining table fields into a single model field #1632
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…