Krishan V
Krishan V

Reputation: 83

Object of type 'Query' is not JSON serializable

This is my routes.py

@app.route('/test', methods=['POST', 'GET'])
def test():
    # form = BrandChoice()
    # email = request.form['email']
    # name = request.form['name']
    choice = request.form['choice']
    print(choice)
    q = session.query(Brand.brand).filter(Brand.pid == choice)
    print(q)
    return jsonify({'choice': q })

And this is my test.js file

$(document).ready(function() {
$('form').on('submit', function(event) {
    $.ajax({
        data : {
            name : $('#nameInput').val(),
            email : $('#emailInput').val(),
            choice : $('#brandInput').val()
        },
        type : 'POST',
        url : '/test'
    })
    .done(function(data) {
        if (data.error) {
            $('#errorAlert').text(data.error).show();
            $('#successAlert').hide();
        }
        else {
            $('#errorAlert').text(data.choice).show();
            $('#successAlert').text(data.name).show();
            // $('#errorAlert').hide();
        }
    });
    event.preventDefault();
});

});

I don't quite get why is it that I cannot get the query result to show up. If I were to replace my 'q' with name for example, it works as intended.

How do I go about returning my query result so that I can display it in my errorAlert?

Upvotes: 2

Views: 6143

Answers (1)

Krishan V
Krishan V

Reputation: 83

Thank you for the help everyone. I understand the issue with my code right now. q is a Query object. I did not even execute the query.

    type_pid = session.query(LenSize.type_pid).filter(LenSize.pid == choice)
    type_pid_result = session.execute(type_pid)
    type_pid_count = type_pid_result.first()[0]
    print(type_pid_count)
    q = session.query(Type.initial).filter(Type.pid == type_pid_count)
    print(q)
    result = session.execute(q)
    print(result)
    id_count = result.first()[0]
    print(id_count)
    return jsonify({'name': id_count})

The amendments I have made was to execute my query and in return I would get a result proxy. Apply the first() method to obtain my desired output. That output was JSON serialisable. No changes were really made to my js file. A simplified version of my correction is below. Hope this helps!

q = session.query(Model.id).filter(Model.pid == choice)
result = session.execute(q)
row_id = result.first()[0]

Upvotes: 2

Related Questions