Can't load JSON data to jQuery sqlalchemy-data

2019-02-24 20:11发布

I'm having troubles on loading JSON data to a datatable. Here it is my Python code to perform that (do the query to the database and return that data with jsonify):

@users_blueprint.route('/data')
def data():
"""Return server side data."""
# defining columns
columns = [
    ColumnDT(User.firstname),
    ColumnDT(User.lastname),
    ColumnDT(User.email),
    ColumnDT(User.urole)
]

# defining the initial query
users = db.session.query(User).all()

# GET parameters
params = request.args.to_dict()

# instantiating a DataTable for the query and table needed
rowTable = DataTables(params, users, columns)

print "AHHAX"
print json.dumps(rowTable.output_result())
# returns what is needed by DataTable
return jsonify(rowTable.output_result())

Then, I have a jinja2 template (usersAdminSection.html) with the table format and the ajax request:

{% block extra_stylesheets %}
<link href="https://cdn.datatables.net/1.10.13/css/jquery.dataTables.css" rel="stylesheet">
{% endblock %}

{% block content %}
<div class="row">
<div class="col-lg-12">
  <table id="dt_110x" class="display" cellspacing="0" width="100%">
    <thead>
      <tr>
        <th>First Name</th>
        <th>Last Name</th>
        <th>Email</th>
        <th>Role</th>
      </tr>
    </thead>
    <tbody></tbody>
  </table>
</div>
</div>
{% endblock %}

{% block extra_javascripts %}
<script src="https://cdn.datatables.net/1.10.13/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" charset="utf-8">
$(document).ready(function(){
  var table = $('#dt_110x').DataTable({
    "processing": true,
    "serverSide": true,
    "ajax": "{{ url_for('users.data') }}"
  });
});
</script>
{% endblock %}

So, when I refresh that template/page I get a alert dialog telling me:

"DataTables warning: table id=dt_110x - 'list' object has no attribute 'add_columns'"

And so, the data is being infinitely processed without any return (0 records).

Any help would be appreciated,

Best regards.

1条回答
Summer. ? 凉城
2楼-- · 2019-02-24 20:59

Try and pass query() without attributes (i.e. your mapped class) and use select_from(). But above all, you must avoid to append all() at the end. Datatables, as far I can understand, accepts sqlalchemy objects and does the job for you. In your case, this should work:

query = db.session.query().select_from(Feature)

Except for this line, your code should run without problems.

查看更多
登录 后发表回答