ETest-Vue-FastAPI/Row对象转换错误修复.md

58 lines
1.5 KiB
Markdown
Raw Normal View History

# Row 对象转换错误修复
## 错误信息
```
'dict' object has no attribute '_mapping'
```
## 问题原因
`PageUtil.paginate` 可能已经将 Row 对象转换为字典了,我们再次尝试转换时出错。
## 修复方案
添加类型检查,只在需要时才转换:
```python
# 执行查询并转换为字典列表
result = await PageUtil.paginate(db, query, query_object.page_num, query_object.page_size, is_page)
# 如果是分页查询,需要转换 rows 为字典
if is_page and hasattr(result, 'rows') and result.rows:
# 检查第一行是否已经是字典
if not isinstance(result.rows[0], dict):
result.rows = [dict(row._mapping) if hasattr(row, '_mapping') else dict(row) for row in result.rows]
elif not is_page and result:
# 检查第一行是否已经是字典
if not isinstance(result[0], dict):
result = [dict(row._mapping) if hasattr(row, '_mapping') else dict(row) for row in result]
return result
```
## 修复逻辑
1. **检查是否为空**: 先检查 `result.rows``result` 是否为空
2. **检查类型**: 检查第一行是否已经是字典
3. **条件转换**: 只在不是字典时才转换
4. **安全转换**: 使用 `hasattr` 检查是否有 `_mapping` 属性
## 验证步骤
### 1. 重启后端服务
```bash
cd ruoyi-fastapi-backend
python main.py
```
### 2. 测试 API
```bash
curl http://localhost:9099/system/test_work_order/list
```
### 3. 检查响应
应该返回正常的 JSON 数据,不再报错。
## 完成时间
2026-01-09 01:50