Issue
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 .
Solution
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.
Answered By - funnydman
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.