the values of ENUM type in SQLAlchemy with PostgreSQL is the variable not the value?
23:16 10 Jul 2024

so my problem is i am trying to make an enum with int values but it didn't work.

first of all, this is the code.

class UserRole(enum.IntEnum):
    publisher = 4
    editor = 3
    manager = 2
    admin = 1 


class User(Base):
    __tablename__ = "user"

    id = Column(Integer, primary_key=True, index=True)
    email = Column(String, unique=True, nullable=False, index=True)
    username = Column(String, unique=True, nullable=False, index=True)
    hashed_password = Column(String, nullable=False)
    user_role = Column(Enum(UserRole), default=UserRole.reader)

now when i create user, go to see user_role i found it admin not 1 i though it might be a cache so i deleted all cache and recreated the database.

until i tried to change one of variables and found that the values of enum that stored on database are the variables itself not the value.

please help me how i can store the enum data as an int on database.

my last attempt was

class UserRole(enum.IntEnum):
    reader: int = 7
    Pro_reader: int = 6
    publisher: int = 5
    editor: int = 4
    small_manager: int = 3
    big_manager: int = 2
    admin: int = 1

and didn't work.

python postgresql sqlalchemy enums fastapi