arg061203
arg061203

Reputation: 1

How to load in new fields after Flask SQLAlchemy Database migration?

When initially setting up my application, I started with a database that had only two fields. After working on it, I wanted to expand that to eight fields. I went through the necessary steps, updating my app.py and script.js files and doing flask db init, flask db migrate, and flask db upgrade, and all went well.

However, when then trying to call on and display data in the other fields I added, all values were null:

100
: 
away_team
: 
null
description
: 
null
first_innings_score
: 
"174/4"
home_team
: 
null
match_id
: 
null
result
: 
null
season
: 
null
second_innings_score
: 
"150"
[[Prototype]]
: 
Object

The only fields that weren't null were first_innings_score and second_innings_score, which are the two fields I had in the database prior to the migration.

I tried adjusting my app.py file and script.js file to show what I needed to. The JS file has a Plotly scatter plot, and I was attempting to expose other fields upon hovering on a point:

text: data.map(d => {
                return `
                    <b>${d.description}</b><br>
                    <span style="font-size: 12px; font-style: italic;">${d.name}</span> | ${d.result}
                `;
            })

In my app.py file, I updated the class:

class Match(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    season = db.Column(db.String(255))
    match_id = db.Column(db.String(255))
    description = db.Column(db.String(255))
    home_team = db.Column(db.String(255))
    away_team = db.Column(db.String(255))
    first_innings_score = db.Column(db.String(255))
    second_innings_score = db.Column(db.String(255))
    result = db.Column(db.String(255))

I updated the way data was loaded:

def load_data_to_db(csv_file):
    df = pd.read_csv(csv_file)
    matches_data = df.to_dict(orient='records')
    
    # Create all tables if they don't exist
    db.create_all()

    for match in matches_data:
        db.session.add(Match(season=match['season'],
                             match_id=match['id'],
                             ... # you get the idea
                             result=match['result']))
    db.session.commit()

And I updated the way data was returned:

@app.route('/data')
def data():
    matches = Match.query.all()
    ipl_data = [{
                "season": match.season, 
                "match_id": match.match_id, 
                ... # you get the idea
                } 
            for match in matches]
    return jsonify(ipl_data)

I think the issue might be with the migration itself. Would love some help!

Upvotes: 0

Views: 28

Answers (0)

Related Questions