python - 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
解决方案
您可以使用.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 相同的记录。这会导致错误。
推荐阅读
- c# - MVC EditorTemplate 绑定不适用于同一页面中的 2 个元素
- python - ModuleNotFoundError: No module named 'Pillow'
- c# - 是否可以使用 .Net EF Core 从现有数据库加载部分对象方案?
- php - 如何为可下载的产品链接(woocommerce)创建简码?
- api - 在点击 NEXMO 的发布请求时,我得到了 {"type":"UNAUTHORIZED","error_title":"Unauthorized"}
- excel - 通过查找找到最接近的号码?
- sql-server - 在 SSIS 中,如何查找值的 ID,如果不匹配,则插入值并返回 ID
- vaadin - 在 Vaadin 14 应用程序中执行 JS 代码什么都不做
- yocto - Jetson Nano 和 Yocto/poky Zeus
- javascript - SignalR 核心 - 尝试将 clientId 传递给 Hub,无法弄清楚如何接收