Skip to content

str typed attribute doesn't get value of Enum field #105

Closed

Description

@Stamper

First Check

  • I added a very descriptive title to this issue.
  • I used the GitHub 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

import enum
from sqlmodel import Field, Column, SQLModel


class FileState(enum.Enum):
    new = "New"
    validated = "Validated"


class File(SQLModel, table=True):
    name: str = Field(index=True)
    state: str = Field(
        sa_column=Column(
            Enum(FileState),
            default=None,
            nullable=True,
            index=True
        )
    )

with Session(engine) as session:
    statement = select(File).where(File.name == name)
    result = session.exec(statement).first()

assert result.state == FileState.validated  # not 'validated'

Description

  • create and save a File instance
  • select record by name
  • state attr value is not a string, but a FileState instance

Operating System

Linux

Operating System Details

No response

SQLModel Version

0.0.4

Python Version

3.9

Additional Context

No response

Activity

  1. fletcheaston commented on Sep 24, 2021

    @fletcheaston

    If you use this (below), does it work?

    class FileState(str, enum.Enum):
        new = "New"
        validated = "Validated"
    
    
    class File(SQLModel, table=True):
        name: str = Field(index=True)
        state: FileState = Field(
            sa_column=Column(
                Enum(FileState),
                default=None,
                nullable=True,
                index=True
            )
        )
    

    FileState inherits from the string class, so you do comparisons like assert result.state == "New" without throwing an exception (although that doesn't help with enum validation in your IDE). Validation in your IDE, mypy, etc. comes from setting the state type hint to FileState.

  2. tiangolo commented on Aug 30, 2022

    @tiangolo
    Member

    Hey there! This might have been solved in #165, available since SQLModel 0.0.7.

    I tried running your example code but it seems it's missing imports and variables so I can't run it. If you're still having issues, please create a self-contained example that I can run to see your exact problem. 🤓

  3. github-actions commented on Sep 10, 2022

    @github-actions
    Contributor

    Assuming the original need was handled, this will be automatically closed now. But feel free to add more comments or create new issues or PRs.

  4. gitpushdashf commented on Apr 28, 2023

    @gitpushdashf

    I'm running into this as well. I made an example for this.

    from enum import StrEnum, auto
    from typing import Annotated
    
    from sqlmodel import Session, SQLModel, Field, create_engine
    
    
    # str, Enum is also affected.
    # Enum seems to work fine, however there's many reasons to use str, Enum or StrEnum.
    class AnEnum(StrEnum):
        FIRST = auto()
        SECOND = auto()
    
    
    class Thing(SQLModel, table=True):
        id: Annotated[int, Field(primary_key=True)]
        an_enum: AnEnum
    
    
    def test() -> None:
        a_thing = Thing(id=1, an_enum=AnEnum.FIRST)
        assert a_thing.an_enum == AnEnum.FIRST
        assert isinstance(a_thing.an_enum, AnEnum)
    
        # Postgres also appears to be affected.
        engine = create_engine("sqlite://")
        SQLModel.metadata.create_all(engine)
        with Session(engine) as session:
            assert a_thing.an_enum == AnEnum.FIRST
            assert isinstance(a_thing.an_enum, AnEnum)
            session.add(a_thing)
            session.commit()
            assert a_thing.an_enum == AnEnum.FIRST
    
            # Right after commit, the type changes from AnEnum to str
            assert isinstance(a_thing.an_enum, AnEnum)
    
            same_thing_from_db = session.get(Thing, 1)
            assert same_thing_from_db is not None
            assert same_thing_from_db.an_enum == AnEnum.FIRST
            assert isinstance(same_thing_from_db.an_enum, AnEnum)
    
        print("Success!")
    
    
    if __name__ == "__main__":
        test()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    answeredquestionFurther information is requested

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions