在多表连接查询时,出现下列问题:
[E 200702 18:42:49 web:1524] Uncaught exception POST /accountant/order (127.0.0.1)
Traceback (most recent call last):
File "/usr/local/lib/python3.7/site-packages/tornado/web.py", line 1443, in _execute
result = method(*self.path_args, **self.path_kwargs)
File "/Users/morika/Desktop/pf.senguo.cc/pfsource/libs/webbase.py", line 95, in wrapper
return method(self, *args, **kwargs)
File "/Users/morika/Desktop/pf.senguo.cc/pfsource/handlers/accountant.py", line 3456, in post
return self.get_order_list(shop_id)
File "/Users/morika/Desktop/pf.senguo.cc/pfsource/libs/webbase.py", line 95, in wrapper
return method(self, *args, **kwargs)
File "/Users/morika/Desktop/pf.senguo.cc/pfsource/handlers/boss_accountant.py", line 321, in get_order_list
print(account_info.id)
AttributeError: 'list' object has no attribute 'id'
原始代码如下:
if goods_id_list:
account_info = session.query(Accountinfo). \
join(GoodsSalesRecord, GoodsSalesRecord.salesman_id == Accountinfo.id) \
.filter(GoodsSalesRecord.goods_id.in_(goods_id_list)) \
.all()
print(account_info)
salesman_info["salesman_id"] = account_info.id
salesman_info["salesman_name"] = account_info.nickname
salesman_info["salesman_sex"] = account_info.sex
salesman_info["salesman_wximgurl"] = account_info.headimgurl
打印出结果:
[<dal.models.Accountinfo object at 0x12009aa90>, <dal.models.Accountinfo object at 0x12009ab10>]
但同样报错,提示AttributeError: ‘list’ object has no attribute ‘id’
原因是查询时使用all()方法,即查询所有符合条件的对象,在打印结果之后读取对象的元素。
从打印结果来看,是一个list,里面有两个acctountinfo 对象,即
salesman_info = [model1, model2]
所以在后面读取model对象的元素时,没有获取到
解决方法是对列表切片读取或者查询时至获取符合条件的第一个对象,即查询时使用first() 而不是all()
if goods_id_list:
account_info = session.query(Accountinfo). \
join(GoodsSalesRecord, GoodsSalesRecord.salesman_id == Accountinfo.id) \
.filter(GoodsSalesRecord.goods_id.in_(goods_id_list)) \
.all()
salesman_info["salesman_id"] = account_info.id
salesman_info["salesman_name"] = account_info.nickname
salesman_info["salesman_sex"] = account_info.sex
salesman_info["salesman_wximgurl"] = account_info.headimgurl
问题即可解决。