D
D
domanskiy2020-10-20 13:56:30
Flask
domanskiy, 2020-10-20 13:56:30

How to serialize Decimal type data from SQLAlchemy?

I'm making a small application on Flask
ORM SQLAlchemy
DB MySQL

Used flask-marshmallow to serialize data output from the database in json format
But I came across the fact that flask-marshmallow does not want to serialize Decimal.
Error : TypeError: Object of type Decimal is not JSON

serializable

class FormThickness(db.Model):
    """Таблица толщин форм"""
    __tablename__ = 'form_thicknesses'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    thickness = db.Column(db.DECIMAL(10, 4), unique=True, nullable=False)
    form_types = db.relationship('FormType', backref=db.backref('form_types'))

    def __repr__(self):
        return f'<{self.thickness}>'


Scheme:
from models import *
from app import ma

class FormThicknessSchema(ma.SQLAlchemySchema):
    class Meta:
        model = FormThickness
        id = ma.auto_field()
        thickness = ma.auto_field()

        include_fk = True
        load_instance = True
        sqla_session = db.session


Can you tell me how to make flask-marshmallow serialize Decimal ?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question