1

I am trying to query on the models.

For example model name called "Demo", i want to get all the records of the table.

class Demo(db.Model):

   __tablename__ = "demo"

   field_1 = db.Column(db.String(255), nullable=False)
   field_2 = db.Column(db.String(255), nullable=False)

now i am querying like

records = Messages.query.all()

and i am trying to send the records as response, so i am facing this error. I am new to flask, please help me to sort it out.

amar
  • 21
  • 1
  • 3

1 Answers1

6

SQLAlchemy returns a ResultProxy object, the simplest/easiest way to handle this is to serialize this on the fly. Many python datatypes do not serialize natively to JSON for obvious reasons.

To get this to output cleanly try this:

def serialize_message(msg):
    return {
        "field_str": msg.field_str,
        "field_int": int(msg.field_int),
        "field_dt": msg.field_dt.strftime("%Y%m%d"),
    }

records = [serialize_message(z) for z in Messages.query]

This way you can modify types as needed for things like python datetime, or other special types that don't natively serialize to JSON.

A more advanced way would be to attach the serialization method directly to the model definition, e.g.:

class Demo(db.Model):
    __tablename__ = "demo"
    field_str = db.Column(db.String(255), nullable=False)
    field_int = db.Column(db.Integer, nullable=False)
    field_dt = db.Column(db.DateTime, nullable=False)

    def to_json(self):
        return {
            "field_str": self.field_str,
            "field_int": int(self.field_int),
            "field_dt": self.field_dt.strftime("%Y%m%d"),
        }

Then you can use this directly as:

records = [z.to_json() for z in Messages.query]
abigperson
  • 5,252
  • 3
  • 22
  • 25