简体   繁体   English

flask-sqlalchemy:在2个表之间映射数据

[英]flask-sqlalchemy: map data between 2 tables

I have a following two tables in a SQLite3 database: 我在SQLite3数据库中有以下两个表:

class Golfer(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100), unique=True, nullable=True)
    scores = db.relationship('Score', backref='associated_golfer', lazy='dynaic')

class Score(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    score = db.Column(db.Integer, nullable=False)
    golfer_name = db.Column(db.String(100), db.ForeignKey('golfer.name'), nullable=False)

My Golfer and Score tables contain the following data respectively: 我的GolferScore表分别包含以下数据:

id|name
1|Johnny Metz
2|Cody Blick
3|Zack Bailey

id|score|golfer_name
1|71|Johnny Metz
2|72|Cody Blick
3|68|Cody Blick
4|70|Zack Bailey
5|73|Zack Bailey
6|66|Johnny Metz

I'm using Flask-SQLAlchemy to fetch the data from these tables. 我正在使用Flask-SQLAlchemy从这些表中获取数据。 I want to map each name in the Golfer table to all of their scores in the Score table. 我想将Golfer表中的每个名称映射到Score表中的所有Score Here's what I'm doing so far but it's very messy and inefficient, especially as my data grows: 到目前为止,这是我正在做的事情,但是它非常混乱且效率低下,尤其是随着数据的增长:

golfers = Golfer.query.all()  # get list of all rows in Golfer table
scores = Score.query.all()  # get list of all rows in Score table
golfer_to_scores = {}
for golfer in golfers:
    golfer_to_scores[golfer] = []
    for score in scores:
        if score.golfer_name == golfer.name:
            golfer_to_scores[golfer].append(score)
print(golfer_to_scores)
# {<Golfer obj>: [<Score obj>, <Score obj>], ...}

Is there a simpler way using a SQL operation via Flask-SQLAlchemy? 是否有通过Flask-SQLAlchemy使用SQL操作的更简单方法? Maybe generate a column in the Golfer table which stores a list of all the scores (aka rows in Score table) associated with that golfer? 也许产生在一列Golfer存储的所有得分(在又名行的名单表Score与高尔夫球手关联表)?

If relationships are configured properly then just: 如果关系配置正确,则:

golfer_to_scores = {golfer: list(golfer.scores) for golfer in Golfer.query.all()}

Though it would do one query per golfer, so you may want to do a join. 尽管它将对每个高尔夫球手进行一次查询,所以您可能想要进行加入。

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

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