【问题标题】:Object of type 'Query' is not JSON serializable“查询”类型的对象不是 JSON 可序列化的
【发布时间】:2019-07-11 02:17:29
【问题描述】:

这是我的路线.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 中显示它?

【问题讨论】:

  • 并非所有对象都可以序列化为 JSON,这就是您的代码中发生的情况。
  • 我认为开箱即用的只有列表/元组、字典、布尔值、字符串和数字可以序列化为 JSON。这些可以用原生类型的 JSON 来表示。对于任何复杂类型,您可以查看此问题Method to serialize custom object to JSON in Python
  • 您的 q 是一个 Query 对象。您可以使用Query.all() 将其具体化为一个列表,但结果可能仍然不是 JSON 可序列化的。

标签: javascript json flask sqlalchemy


【解决方案1】:

感谢大家的帮助。我现在了解我的代码的问题。 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]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-11
    • 2021-07-04
    • 2021-12-10
    • 1970-01-01
    • 2021-09-27
    • 2019-09-04
    • 2019-01-12
    相关资源
    最近更新 更多