Python函数将在最后一次迭代中循环但出错

时间:2015-08-19 19:12:52

标签: python-2.7 orm sqlalchemy

在下面的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'`

1 个答案:

答案 0 :(得分:0)

此错误的最可能原因是Shelter.id值中存在 hole 。例如,表格中可能包含id值为[1, 2, 3, 4, 5, 7]的行。当您到达最后一个元素时,您将尝试找到ID为6的Shelter,但它不存在。

原则上,您的代码现在的工作方式是做出一个非常大胆的假设,即数据库中的所有行都具有从id开始的连续1值。但事实并非如此。相反,您可以直接遍历实例,而不是逐个加载它们:

def vacantShelter():
    shelters = session.query(Shelter).all()
    for shelter in shelters:
        if(shelter.max_capacity >= getShelterOccupancy(shelter.id)):
            print shelter.name + " has available space"
        else:
            print shelter.name + " is full! :("

此外,它更清洁。