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

时间:2019-01-05 12:08:41

标签: python sqlalchemy flask-sqlalchemy

我正在尝试在所有行中查询名为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())

2 个答案:

答案 0 :(得分:1)

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

msg.url

问题的症结在于,如果数据库中不存在该节目,您想创建一个新的result = SomeModel.query.with_entities(SomeModel.col1, SomeModel.col2) 实例。

如果您最终在数据库中找到很多节目,那么查询数据库中所有节目并循环浏览每个潜在的新节目的结果可能会变得效率很低,而通过身份查找对象是RDBMS最好的选择! / p>

此函数将检查对象是否存在,如果不存在则创建它。受this answer的启发:

Show

所以您的示例如下:

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

如果您真的想先查询所有节目,则可以使用set instead of a list来加快收录测试,而不是将所有ID放入列表中。

例如:

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'])

答案 1 :(得分:0)

我已决定使用上述方法,并将所需的数据提取到列表中,然后将每个节目与列表进行比较。

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