Skip to content

How to mark a model field as "non-persisted", i.e. to not be pushed to the DB? #147

Closed
@JLHasson

Description

@JLHasson

First Check

  • I added a very descriptive title to this issue.
  • I used the search to find a similar issue and didn't find it.
  • I searched the SQLModel documentation, with the integrated search.
  • I already searched in Google "How to X in SQLModel" and didn't find any information.
  • I already read and followed all the tutorial in the docs and didn't find an answer.
  • I already checked if it is not related to SQLModel but to Pydantic.
  • I already checked if it is not related to SQLModel but to SQLAlchemy.

Commit to Help

  • I commit to help with one of those options 👆

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    questionFurther information is requested

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions