Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unpack enum value used in Flask Sqlaclhemy?

I have enum defined .

from enum import Enum
class Status(Enum):
    pending = 'PENDING'
    processed = 'PROCESSED'
    delivered = 'DELIVERED'

In model.py

class Activity(db.Model):

    __tablename__ = 'activity'
    id = db.Column(db.Integer, primary_key=True))
    message = db.Column(db.String, nullable=False)
    status = db.Column(db.Enum(Status), nullable=False)

in controller.py

jsn_data = request.get_json()
activity_obj = Activity(message=jsn_data['message'], status=jsn_data['status'])

in request json body

{
   "message": 'Hi',
   "status':'pending'
}

So here i want status value "PENDING" store in DB instead of 'pending'. Let me know what i am missing .

like image 324
Vivek Kumar Avatar asked Nov 01 '25 09:11

Vivek Kumar


1 Answers

The documentation has an example:

import enum
class MyEnum(enum.Enum):
    one = 1
    two = 2
    three = 3

t = Table(
    'data', MetaData(),
    Column('value', Enum(MyEnum))
)

Above, the string names of each element, e.g. “one”, “two”, “three”, are persisted to the database; the values of the Python Enum, here indicated as integers, are not used; the value of each enum can therefore be any kind of Python object whether or not it is persistable.

In order to persist the values and not the names, the Enum.values_callable parameter may be used. For a simple enumeration that uses string values, a callable such as

lambda x: [e.value for e in x] is sufficient.

So, to use values instead of keys specify values_callable:

t = Table(
    'data', MetaData(),
    Column('value', Enum(MyEnum, 
     values_callable=lambda x: [str(e.value) for e in MyEnum])
    )
   )
)

I would suggest to use echo=True with create_engine to see what SQL was generated.

like image 175
funnydman Avatar answered Nov 03 '25 23:11

funnydman