Reputation: 563
i'm very new with sqlalchemy-datatables and now i try to create html table which using datatables plugin to contain data from database that i have query and this is my code.
routes.py
@app.route('/load_db', methods=['GET', 'POST'])
def load_db():
columns = [
ColumnDT(Customers.customer_code),
ColumnDT(Customers.customer_name),
]
query = db.session.query(Customers)
params = request.args.to_dict()
rowTable = DataTables(params, query, columns)
return jsonify(rowTable.output_result())
models.py
class Customers(db.Model):
__tablename__ = 'customers'
customer_code = db.Column(db.String(30), primary_key=True)
customer_name = db.Column(db.String(100))
customer_address = db.Column(db.String(200))
customer.html
$(document).ready(function () {
$('#customertable').DataTable({
"processing": true,
"serverSide": true,
"ajax": "/load_db"
});
});
When i render the template it error like this.
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/json/encoder.py", line 179, in default
raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type Customers is not JSON serializable
This is the value of rowTable.output_result()
when i print it out.
{'draw': '1', 'recordsTotal': '52', 'recordsFiltered': '52', 'data': [{'0': <Customers 1>, '1': '1'}, {'0': <Customers 10>, '1': '10'}, {'0': <Customers 11>, '1': '11'}, {'0': <Customers 12>, '1': '12'}, {'0': <Customers 13>, '1': '13'}, {'0': <Customers 14>, '1': '14'}, {'0': <Customers 15>, '1': '15'}, {'0': <Customers 16>, '1': '16'}, {'0': <Customers 17>, '1': '17'}, {'0': <Customers 18>, '1': '18'}]}
So what is a problem with my code and how can i fix it.
Upvotes: 1
Views: 1099
Reputation: 407
Try change your query into this, db.session.query().select_from(Customer)
. It's what written on sqlalchemy-datatables github page.
I don't have any explanation about what makes them different yet.
Upvotes: 3