First Check
Commit to Help
Example Code
from typing import Optional
from pydantic.fields import PrivateAttr
from sqlmodel import Field, Session, SQLModel, create_engine, select
class Hero(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
_name: str = PrivateAttr() # This field is not committed to the db
secret_name: str
sqlite_file_name = "database.db"
sqlite_url = f"sqlite:///{sqlite_file_name}"
engine = create_engine(sqlite_url, echo=True)
if __name__ == "__main__":
SQLModel.metadata.create_all(engine)
hero_1 = Hero(secret_name="Dive Wilson")
hero_1._name = "hello"
print(hero_1) # Hero will have a _hello attribute
with Session(engine) as session:
session.add(hero_1)
session.commit()
with Session(engine) as session:
statement = select(Hero)
results = session.exec(statement)
for hero in results:
print(hero) # Hero will not have a _hello attribute (when read from the db)
Description
It is unclear how to add fields to a model that should not be written to the DB. I have achieved this by prepending the attribute name with an underscore as shown in the code sample above. I decided to achieve it that way based on how Pydantic handles these private attributes (https://pydantic-docs.helpmanual.io/usage/models/#automatically-excluded-attributes).
If there is a better way to do this I'd love to know. Alternatively I'd love to update the documentation if this is the correct way. I took a look at the file structure a bit but wasn't entirely sure where the best place to add it was, so I decided to open an issue instead of a PR.
Operating System
macOS
Operating System Details
No response
SQLModel Version
0.0.4
Python Version
Python 3.9.5
Additional Context
No response
First Check
Commit to Help
Example Code
Description
It is unclear how to add fields to a model that should not be written to the DB. I have achieved this by prepending the attribute name with an underscore as shown in the code sample above. I decided to achieve it that way based on how Pydantic handles these private attributes (https://pydantic-docs.helpmanual.io/usage/models/#automatically-excluded-attributes).
If there is a better way to do this I'd love to know. Alternatively I'd love to update the documentation if this is the correct way. I took a look at the file structure a bit but wasn't entirely sure where the best place to add it was, so I decided to open an issue instead of a PR.
Operating System
macOS
Operating System Details
No response
SQLModel Version
0.0.4
Python Version
Python 3.9.5
Additional Context
No response