I want to build an API for my project and return everything as JSON using Flask and SQLAlchemy. Unfortunately, SQLAlchemy did not return the query as JSON Seriazeble, so I'm using data classes to solve that problem. The code working and it returns JSON as I wanted. The problem occurs when I try to implement enum column like gender, because the enum column returns an enum object, so it's not JSON Seriazeble again. This is the code:
ActivityLevel.py
class GenderEnum(Enum):
p = 0
l = 1
@dataclass
class ActivityLevel(db.Model):
__tablename__ = "activity_level"
id: int
name: str
gender: GenderEnum
activity_score: float
date_created: str
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(100), nullable=False)
gender = db.Column(db.Enum(GenderEnum), nullable=False)
activity_score = db.Column(
db.Float(precision=3, decimal_return_scale=2), nullable=False
)
date_created = db.Column(db.DateTime, default=datetime.utcnow)
ActivityLevelController.py
from flask import jsonify
from flask_restful import Resource
from models.ActivityLevel import ActivityLevel
class ActivityLevelController(Resource):
def get(self):
try:
activity = ActivityLevel().query.all()
result = {
"activity": activity
}
print(activity)
return jsonify(result)
except Exception as e:
print(e)
return jsonify({"message": "Error again"})
And this is the result of print(activity)
[
ActivityLevel(id=1, name='asdfasdf', gender=<GenderEnum.p: 0>, activity_score=12.0, date_created=datetime.datetime(2022, 8, 12, 10, 54, 58)),
ActivityLevel(id=2, name='qwerqwer', gender=<GenderEnum.l: 1>, activity_score=13.0, date_created=datetime.datetime(2022, 8, 12, 10, 54, 58))
]
As you can see, gender did not return l or p, and it return <GenderEnum.l: 1>. Which is correct as the documentation says https://docs.python.org/3/library/enum.html, when i call GenderEnum.l
it will result just like the response.
What I want to ask is something like this:
- Is there a way to override the return value of
GenderEnum.l
to the value or name by doing something in GenderEnum class? - Is there a way I can get the value or name of GenderEnum when I query the data from the database?
- Or a way to make the query call the gender value or name as the default instead the enum object?
Thank you very much.