我正在编写一个小的Python脚本/应用程序,而我正在尝试使用SQLAlchemy。我唯一的课程是“玩家”,其定义如下:
class Player:
def __init__(self, rating, college, ranking = None, firstName = None, lastName = None):
self.rating = rating
self.college = college
self.ranking = ranking
self.firstName = firstName
self.lastName = lastName
现在我有一个名为databaseFunctions.py的模块,在其中我有这两个函数:
#if player exists, update his rating and ranking; otherwise, add new object to DB
def updateSpecificDBEntry(playerObject, session):
#find player in DB with firstName and lastName
currentPlayer = session.query(Player).filter(firstName == playerObject.firstName).filter(playerObject.lastName == lastName).first()
#set rating = newRating
if currentPlayer.count():
currentPlayer.rating = playerObject.rating
currentPlayer.ranking = playerObject.ranking
else:
addEntryToDB(playerObject, session)
def updateEntireDB(arrayOfPlayerObjects, session):
for player in arrayOfPlayerObjects:
updateSpecificDBEntry(player, session)
这是我的主要方法:
def main():
#create engine (for use by base and session)
engine = databaseFunctions.createEngine()
#create session
session = databaseFunctions.createSession(engine)
#get all players from CSA website
allPlayers = getSortedGender(constants.mainURL, constants.menTeams)
databaseFunctions.updateEntireDB(allPlayers, session)
我的代码实际上一直工作到最后一次函数调用。此时,我收到以下错误:
File "helpfulFunctions.py", line 114, in <module>
main()
File "helpfulFunctions.py", line 107, in main
databaseFunctions.updateEntireDB(allPlayers, session)
File "/Users/benjaminclayman/Desktop/SquashScraper/databaseFunctions.py", line 42, in updateEntireDB
updateSpecificDBEntry(player, session)
File "/Users/benjaminclayman/Desktop/SquashScraper/databaseFunctions.py", line 32, in updateSpecificDBEntry
currentPlayer = session.query(Player).filter(firstName == playerObject.firstName).filter(playerObject.lastName == lastName).first()
NameError: global name 'firstName' is not defined
我有点困惑,因为我正在查询数据库中的所有Player对象,查找其名字与传入的firstName
的{{1}}匹配且其姓氏与{{1}匹配的条目传入的playerObject
。
知道我为什么会收到此错误?
我最初在main()中调用了这个函数,但没有使用它,所以把它取出来了:
lastName
就像我说的那样:
playerObject
然后对def createBase(engine):
Base = declarative_base()
Base.metadata.create_all(engine)
return Base
无所作为。不确定这是否是问题的一部分。
感谢您的帮助, bclayman
答案 0 :(得分:2)
在updateSpecificDBEntry过滤器中,您有:
class="SafeStyles"
变量“firstName”不存在。
看起来你的意思是:
.filter(firstName == playerObject.firstName)
所以你要根据给定的playerObject属性过滤Player列。