Skip to content

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

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
8 tasks done
Stamper opened this issue Sep 20, 2021 · 4 comments
Closed
8 tasks done

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

Stamper opened this issue Sep 20, 2021 · 4 comments
Labels
answered question Further information is requested

Comments

@Stamper
Copy link

Stamper commented Sep 20, 2021

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

@Stamper Stamper added the question Further information is requested label Sep 20, 2021
@fletcheaston
Copy link

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.

@tiangolo
Copy link
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. 🤓

@github-actions
Copy link

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.

@gitpushdashf
Copy link

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
Labels
answered question Further information is requested
Projects
None yet
Development

No branches or pull requests

4 participants