首页 > 解决方案 > TypeError: int() 参数必须是字符串、类似字节的对象或数字,而不是“结果”

问题描述

我正在尝试采用最高的 id 并添加一个来制作新的 id。当我尝试启动它时(它为空,因为那里还没有任何东西)它给了我这个错误:TypeError: int() argument must be a string, a bytes-like object or a number, not 'result'.

@app.route('/new-recipe', methods=['POST'])
def create_recipe(application):
    data = request.get_json()
    current_id = int(db.session.query(func.max(Recipes.id)).first())
    # I've tried without int() too.

    if current_id >= 1:
        new_id = current_id + 1
        new_recipe = Recipes(id=new_id)
        return new_recipe.id
    else:
        new_recipe = Recipes(id=1)
        return new_recipe.id

标签: pythonsqlalchemy

解决方案


您可以使用.scalar()将结果转换为值。

current_id = db.session.query(func.max(Recipes.id)).scalar()

请参阅https://docs.sqlalchemy.org/en/13/orm/query.html#sqlalchemy.orm.query.Query.scalar

但是,我确实对您的方法有意见:最好让数据库为您生成 id,因为当多人同时访问时,像您这样的代码可能会出现不可预测的行为/new-recipe

如果您获得最后一个 id,然后在单独的查询中插入(而不是在数据库事务中),那么其他人可以在您之前插入一条与您尝试插入的 ID 相同的记录。这会导致错误。


推荐阅读