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

2024-10-05 17:43:49 发布

您现在位置:Python中文网/ 问答频道 /正文

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

有没有更好的方法来创建查询来实现这一点?在

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

结果:

^{pr2}$

整个功能的代码:

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())

Tags: the方法inidshowallfilterquery
2条回答

要查询特定的列值,请看以下问题:Flask SQLAlchemy query, specify column names。下面是顶部答案中给出的示例代码:

result = SomeModel.query.with_entities(SomeModel.col1, SomeModel.col2)

问题的症结在于,如果数据库中不存在一个新的Show实例,则需要创建该实例。在

如果数据库中有很多节目,查询数据库中的所有节目并循环查看每个潜在新节目的结果可能会变得非常低效,而通过标识查找对象是RDBMS最擅长的!在

此函数将检查对象是否存在,如果不存在,则创建它。灵感来自this answer

^{pr2}$

所以你的例子应该是:

def add_if_not_exists(model, **kwargs):
    if not model.query.filter_by(**kwargs).first():
        instance = model(**kwargs)
        db.session.add(instance)

for show in show_details:
    add_if_not_exists(Show, id=show['id'])

如果您真的想预先查询所有显示,而不是将所有的id放入一个列表中,您可以使用一个set instead of a list来加快包含测试。在

例如:

show_compare = {item.show_id for item in Show.query.all()}
for show in show_details:
   # ... same as your code

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

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

相关问题 更多 >