sqlalchemydatatables TypeError:类型为Customer的对象不可JSON序列化

2024-06-01 07:04:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用SQLAlchemy-DataTables构建一个具有服务器端处理的表

   @app.route("/data", methods=['GET'])
        def data():
        columns = [
            ColumnDT(Customer.id),
            ColumnDT(Customer.Email),
        ]
        query = db.session.query(Customer)
        params = request.args.to_dict()
    
        
        rowTable = DataTables(params, query, columns)
        print(query , file=sys.stdout)
        return jsonify(rowTable.output_result()) 

在调试模式下运行时,我可以看到rowTable.output_result()返回:

{'draw': '1', 'recordsTotal': '13997', 'recordsFiltered': '13997', 'data': [{'0': <Customer#1>, '1': 1}, {'0': <Customer#2>, '1': 2}, {'0': <Customer#3>, '1': 3}, {'0': <Customer#4>, '1': 4}, {'0': <Customer#5>, '1': 5}, {'0': <Customer#6>, '1': 6}, {'0': <Customer#7>, '1': 7}, {'0': <Customer#8>, '1': 8}, {'0': <Customer#9>, '1': 9}, {'0': <Customer#10>, '1': 10}]}

但我得到了以下错误: TypeError:Customer类型的对象不可JSON序列化

我按照文档做了所有的事情,所以我不明白为什么这不起作用


Tags: columnsappoutputdatasqlalchemy服务器端customerparams
1条回答
网友
1楼 · 发布于 2024-06-01 07:04:46

问题是您试图调用python对象<Customer>上的jsonify()。要了解原因,请查看您的输出:

{
  'draw': '1',
  'recordsTotal': '13997',
  'recordsFiltered': '13997',
  'data': [{
    '0': < Customer1 > ,
    '1': 1
  }, {
    '0': < Customer2 > ,
    '1': 2
  }, {
    '0': < Customer3 > ,
    '1': 3
  }, {
    '0': < Customer4 > ,
    '1': 4
  }, {
    '0': < Customer5 > ,
    '1': 5
  }, {
    '0': < Customer6 > ,
    '1': 6
  }, {
    '0': < Customer7 > ,
    '1': 7
  }, {
    '0': < Customer8 > ,
    '1': 8
  }, {
    '0': < Customer9 > ,
    '1': 9
  }, {
    '0': < Customer10 > ,
    '1': 10
  }]
}

'data'内部,有一些对象无法被json.dumps()自动序列化,而这正是jsonify()有效地为您所做的

要解决此问题,您需要修改输出,以便json.dumps()具有更无聊的数据类型。例如:

for item in rowTable.output_result()['data']:
    item['0'] = {
        'customer_id': item['0'].id,
        # and so on for the other properties you're interested in
    }

您还可以在<Customer>类上编写一个函数,自动序列化所有重要属性,然后执行如下操作:

for item in rowTable.output_result()['data']:
    item['0'] = item['0'].serialized

关于如何在课堂上做到这一点的示例:

class Customer(Model):
    id = Column(Integer)
    # etc...

    @property
    def serialized(self):
        return {
            'id': self.id
        }


相关问题 更多 >