【发布时间】:2015-11-13 05:49:07
【问题描述】:
在以下 Python 函数中,我使用 Python 2.7.6 和 SQLAlchemy 作为 ORM。我很困惑为什么即使函数循环通过,我仍然会收到以下错误。
def vacantShelter():
#Used to stay in bounds of the all the entries in the DB
shelterCount = session.query(Shelter).count
shelter_id = 1
print "Here are the Shelter results:"
while(shelter_id<=shelterCount):
shelter = session.query(Shelter).filter(Shelter.id == shelter_id).first()
if(shelter.max_capacity >= getShelterOccupancy(shelter_id)):
print shelter.name + " has available space"
else:
print shelter.name + " is full! :("
shelter_id = shelter_id + 1
让我感到困惑的是,考虑到有结果,它一开始运行正常,我不明白为什么在最后一次迭代中它会失败或如何处理它。
`Here are the Shelter results:
Oakland Animal Services has available space
San Francisco SPCA Mission Adoption Center is full! :(
Wonder Dog Rescue has available space
Humane Society of Alameda is full! :(
Palo Alto Humane Society is full! :(
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "pup_test.py", line 82, in vacantShelter
if(shelter.max_capacity >= getShelterOccupancy(shelter_id)):
AttributeError: 'NoneType' object has no attribute 'max_capacity'`
【问题讨论】:
-
Shelter.id值中是否存在 漏洞?例如,可能存在id值为[1, 2, 3, 4, 5, 7]的行。当你到达最后一个元素时,你会尝试找到一个id为6的Shelter,但它并不存在。 -
我在创建庇护所对象后添加了以下代码,我的错误不再存在:
if not shelter: return感谢@van 的提示。这是最有效的举措吗? -
由于我想展示的代码示例,我将添加一个答案。
-
我认为这根本不是正确的举动,因为您的解决方案实际上会错过一些
id最高的Shelters值。
标签: python-2.7 orm sqlalchemy