gpt4 book ai didi

Python Flask 和 SQLAlchemy,从列中选择所有数据

转载 作者:行者123 更新时间:2023-12-01 01:18:47 26 4
gpt4 key购买 nike

我正在尝试查询所有行中名为 show_id 的列。然后,我想将要添加到数据库中的每个潜在项目与结果进行比较。现在,我能想到的最简单的方法是检查每个节目是否在结果中。如果是这样,则通过等。但是,以下代码片段的结果将作为对象返回。所以这个检查失败了。

是否有更好的方法来创建查询来实现此目的?

shows_inDB = Show.query.filter(Show.show_id).all()
print(shows_inDB)

结果:

<app.models.user.Show object at 0x10c2c5fd0>, 
<app.models.user.Show object at 0x10c2da080>,
<app.models.user.Show object at 0x10c2da0f0>

整个函数的代码:

def save_changes_show(show_details):
"""
Save the changes to the database
"""
try:
shows_inDB = Show.query.filter(Show.show_id).all()
print(shows_inDB)

for show in show_details:

#Check the show isnt already in the DB
if show['id'] in shows_inDB:
print(str(show['id']) + ' Already Present')
else:

#Add show to DB
tv_show = Show(
show_id = show['id'],
seriesName = str(show['seriesName']).encode(),
aliases = str(show['aliases']).encode(),
banner = str(show['banner']).encode(),
seriesId = str(show['seriesId']).encode(),
status = str(show['status']).encode(),
firstAired = str(show['firstAired']).encode(),
network = str(show['network']).encode(),
networkId = str(show['networkId']).encode(),
runtime = str(show['runtime']).encode(),
genre = str(show['genre']).encode(),
overview = str(show['overview']).encode(),
lastUpdated = str(show['lastUpdated']).encode(),
airsDayOfWeek = str(show['airsDayOfWeek']).encode(),
airsTime = str(show['airsTime']).encode(),
rating = str(show['rating']).encode(),
imdbId = str(show['imdbId']).encode(),
zap2itId = str(show['zap2itId']).encode(),
added = str(show['added']).encode(),
addedBy = str(show['addedBy']).encode(),
siteRating = str(show['siteRating']).encode(),
siteRatingCount = str(show['siteRatingCount']).encode(),
slug = str(show['slug']).encode()
)
db.session.add(tv_show)

db.session.commit()
except Exception:
print(traceback.print_exc())

最佳答案

我决定使用上面的方法,将我想要的数据提取到一个列表中,将每个节目与列表进行比较。

show_compare = []
shows_inDB = Show.query.filter().all()
for item in shows_inDB:
show_compare.append(item.show_id)


for show in show_details:
#Check the show isnt already in the DB
if show['id'] in show_compare:
print(str(show['id']) + ' Already Present')
else:
#Add show to DB

关于Python Flask 和 SQLAlchemy,从列中选择所有数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54051856/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com