2

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?

Krishan V
  • 83
  • 1
  • 6
  • Not all objects can be serialized as JSON, and that's what's happening in your code. – Pointy Feb 17 '19 at 15:34
  • I think that out of the box only lists/tuples, dicts, booleans, strings and numbers can be serialized to JSON. Those can be represented in native types of JSON. For any complex types you can check this question [Method to serialize custom object to JSON in Python](https://stackoverflow.com/q/24030284/387194) – jcubic Feb 17 '19 at 16:11
  • Your `q` is a `Query` object. You can materialize it to a list using `Query.all()`, though the result may still not be JSON serializable. – Ilja Everilä Feb 17 '19 at 18:51

1 Answers1

2

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]
Krishan V
  • 83
  • 1
  • 6