The Problem:
How can I declare enums in SQLAlchemy version 2 using mapped_column
to enable type hinting and avoid errors like 'ENUM' object has no attribute '__mro__'
during class construction?
The Solutions:
Solution 1: {title}
To declare enums in SQLAlchemy using `mapped_column` (to enable type hinting), you can use the following approach:
from typing import Literal
from typing import get_args
from sqlalchemy import Enum
from sqlalchemy.orm import DeclarativeBase
from sqlalchemy.orm import Mapped
from sqlalchemy.orm import mapped_column
CampaignStatus = Literal["activated", "deactivated"]
class Base(DeclarativeBase):
pass
class Campaign(Base):
__tablename__ = "campaign"
id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True)
status: Mapped[CampaignStatus] = mapped_column(Enum(
*get_args(CampaignStatus),
name="campaignstatus",
create_constraint=True,
validate_strings=True,
))
In this solution, we first create a CampaignStatus
enum using the Literal
type from the typing
module. Then, we define a Campaign
class that inherits from Base
, which is a declarative base class. We use the mapped_column
function to define the id
and status
columns, specifying the data types and constraints. The Enum
class from SQLAlchemy is used to create an enum column for the status
field, and we pass the arguments for the enum type, including the list of enum values, the name of the enum type, and the create_constraint
and validate_strings
flags.
Q&A
How do I declare enums in SQLAlchemy using mapped_column (to enable type hinting)?
Use mapped_column to declare the column and specify the enum type as the argument to mapped_column.
How do I declare enums in SQLAlchemy using mapped_column (to enable type hinting)?
Define the enum as a Python enum class and then pass it to mapped_column as the type argument.