简体   繁体   English

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

[英]Python Flask and SQLAlchemy, selecting all data from a column

I am attempting to query all rows for a column called show_id . 我正在尝试查询所有行以查找名为show_id的列。 I would then like to compare each potential item to be added to the DB with the results. 然后,我想将要添加到数据库中的每个潜在项目与结果进行比较。 Now the simplest way I can think of doing that is by checking if each show is in the results. 现在,我想到的最简单的方法是检查每个节目是否都在结果中。 If so pass etc. However the results from the below snippet are returned as objects. 如果是这样,则通过等等。但是,以下代码段的结果将作为对象返回。 So this check fails. 因此此检查失败。

Is there a better way to create the query to achieve this? 有没有更好的方法来创建查询来实现这一目标?

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

Results: 结果:

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

Code for the entire function: 整个功能的代码:

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

I have decided to use the method above and extract the data I wanted into a list, comparing each show to the list. 我决定使用上述方法,并将所需的数据提取到列表中,然后将每个节目与列表进行比较。

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

For querying a specific column value, have a look at this question: Flask SQLAlchemy query, specify column names . 要查询特定的列值,请看以下问题: Flask SQLAlchemy查询,指定列名 This is the example code given in the top answer there: 这是最上面的答案中给出的示例代码:

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

The crux of your problem is that you want to create a new Show instance if that show doesn't already exist in the database. 问题的症结在于,如果数据库中不存在该节目,则您想创建一个新的Show实例。

Querying the database for all shows and looping through the result for each potential new show might become very inefficient if you end up with a lot of shows in the database, and finding an object by identity is what an RDBMS does best! 如果最终在数据库中显示很多节目,则查询数据库中的所有节目并为每个潜在的新节目遍历结果可能会变得效率很低,而通过标识找到对象是RDBMS最好的选择!

This function will check to see if an object exists, and create it if not. 此函数将检查是否存在对象,如果不存在则创建它。 Inspired by this answer : 受此答案启发:

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

So your example would look like: 因此,您的示例如下所示:

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

If you really want to query all shows upfront, instead of putting all of the id's into a list, you could use a set instead of a list which will speed up your inclusion test. 如果您真的想先查询所有节目,而不是将所有ID放在列表中,则可以使用集合而不是列表 ,这样可以加快收录测试的速度。

Eg: 例如:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM