1

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.

2

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Sorry i got some more question, do you know how to add the button to each column which store customer_code of that row?
You may want to search datatables render. If you've tried that and still got question, then please post another question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.