“查询”类型的对象不可JSON序列化

时间:2019-02-17 15:27:17

标签: javascript json flask sqlalchemy

这是我的路线。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 })

这是我的test.js文件

$(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();
});

});

我不太明白为什么我无法显示查询结果。例如,如果我将“ q”替换为名称,它将按预期工作。

如何返回查询结果,以便将其显示在errorAlert中?

1 个答案:

答案 0 :(得分:0)

谢谢大家的帮助。我现在了解我的代码存在的问题。 q是查询对象。我什至没有执行查询。

    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})

我所做的修改是执行查询,作为回报,我将获得结果代理。应用first()方法获得我想要的输出。该输出是JSON可序列化的。我的js文件没有真正更改。我的更正的简化版本如下。希望这会有所帮助!

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