How to jsonify objects from sqlalchemy?

后端 未结 6 708
离开以前
离开以前 2021-01-21 23:15

I\'m using Flask, SQLAlchemy and javascript. I need to pass the results of my query to javascript in the json format, through AJAX, but I keep getting this error:



        
6条回答
  •  死守一世寂寞
    2021-01-22 00:10

    Using marshmallow-sqlalchemy schemas, I'm generating an object and returning the serializable JSON object as a native method for the model. Here is an example for a class of Customer in SQLAlchemy model.

    from models import db
    import datetime
    from marshmallow_sqlalchemy import ModelSchema
    
    class Customer(db.Model):
        __tablename__ = 'customers'
        __table_args__ = {'schema': 'abc_schema'}
        id = db.Column(db.String(255), primary_key=True)
        created_at = db.Column(db.DateTime, default=datetime.datetime.utcnow)
        firstName = db.Column(db.String())
        lastName = db.Column(db.String())
        def __getitem__(self, item):
            return getattr(self, item)
    
        ## Making the sql alchemy object JSON serailizable
        def JSONSerializableObj(self):
            class BaseSchema(ModelSchema): 
                def on_bind_field(self, field_name, field_obj):
                    field_obj.allow_none = True
    
            class ObjectSchema(BaseSchema): 
                class Meta:
                    model = self
    
            object_schema = ObjectSchema()
            return object_schema.dump(self).data
    

    This way, I'm just reusing this snippet for all models and using the JSONSerializableObj

提交回复
热议问题