【问题标题】:Comparing two tables using flask-sqlalchemy使用 flask-sqlalchemy 比较两个表
【发布时间】:2016-05-18 12:58:58
【问题描述】:

我正在用 python 和烧瓶开始我的冒险。

我正在为 MySQL/MariaDB 任务使用 Flask-SQLAlchemy

class Local(db.Model):
    __tablename__ = 'local'
    id = db.Column("VideoLocalID", db.Integer, primary_key=True)
    file_path = db.Column("FilePath", db.String)
    hash = db.Column("Hash", db.String)

class Remote(db.Model):
    __tablename__ = 'remote'
    id = db.Column("EpisodeID", db.Integer, primary_key=True)
    # hash = db.relationship('Local', backref='hash', lazy='dynamic')
    hash = db.Column("Hash", db.String)
    #hash = db.relationship(db.String, db.ForeignKey('local.hash'))
    percentage = db.Column("Percentage", db.Integer)

我试图让所有不“散列”的项目都不存在于两个表中。我只对本地表中的项目感兴趣。

如你所见,我试图让 FK 工作但没有成功

localv = Local.query.all()
remotev = Remote.query.all()
    for video in localv:
        for video_remote in remotev:
            #checking if there is a match if not adding to list

我认为我的双 for 循环很糟糕。有没有办法加快速度,甚至可以在数据库中而不是在本地进行?

【问题讨论】:

    标签: sql python-2.7 flask flask-sqlalchemy


    【解决方案1】:

    最简洁的方法是

    # get all rows with distinct (unique) hashes from Remote and create a list of hashes.
    remote_hash_list = [item.hash for item in Remote.query.distinct(Remote.hash).all()]
    
    # Now get all Local items that hash is not in remote hashes list
    local_items = Local.query.filter(Local.hash.notin_(remote_hash_list)).all()
    

    【讨论】:

    • 先生,您成就了我的一天。谢谢向导
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-26
    • 2021-02-11
    • 1970-01-01
    相关资源
    最近更新 更多