Sunday, 10 October 2021

In SQL Alchemy ORM How Can I Query a Table that Has ENUM Column and Keep the ENUM?

I have a table in sql db with an id column, and a column called b, which is type enum, and can take values ('example_1', 'example_2').

In python I have an Enum class like this:


class BTypes(Enum):
    EXAMPLE_1 = 'example_1'
    EXAMPLE_2 = 'example_2'

For querying the table, I have an ORM like this:

class Example(Base):
    __tablename__ = "example"
    id = Column(Integer, primary_key=True)
    b = Column(Enum(BTypes).values_callable)

When I do: session.query(Example).all(), the objects that I get back have str type for the b attribute. In other words:

data = session.query(Example).all()
print(data[0].b)
# Outputs
--> 'example_1`

I want that the Example object for the attribute b has an enum type, not str. What is the best way to achieve this?



from In SQL Alchemy ORM How Can I Query a Table that Has ENUM Column and Keep the ENUM?

No comments:

Post a Comment