I'm using Flask-SQLAlchemy to represent a Student. I'm getting a Runtime error when querying my Student object. I've referenced previous posts about this issue, but can't seem to fix it.
Here is my Student class:
class Student(db.Model):
__tablename__ = 'students'
id = db.Column(db.Integer(), primary_key=True)
last_name = db.Column(db.Text(), nullable=False)
first_name = db.Column(db.Text(), nullable=False)
major_1 = db.Column(db.Text(), nullable=False)
major_2 = db.Column(db.Text())
major_3 = db.Column(db.Text())
concentration_1 = db.Column(db.Text())
concentration_2 = db.Column(db.Text())
concentration_3 = db.Column(db.Text())
minor_1 = db.Column(db.Text())
minor_2 = db.Column(db.Text())
minor_3 = db.Column(db.Text())
math_placement_score = db.Column(db.Integer())
high_school_gpa = db.Column(db.Float(),
db.CheckConstraint('high_school_gpa >= 0.0 AND high_school_gpa <= 4.0'))
college_gpa = db.Column(db.Float(),
db.CheckConstraint('high_school_gpa >= 0.0 AND high_school_gpa <= 4.0'))
sat_score = db.Column(db.Integer(),
db.CheckConstraint(f'sat_score >= {app.config["SAT_SCORE_MIN"]} AND sat_score <= {app.config["SAT_SCORE_MAX"]}'))
act_score = db.Column(db.Integer(),
db.CheckConstraint(f'sat_score >= {app.config["ACT_SCORE_MIN"]} AND sat_score <= {app.config["ACT_SCORE_MAX"]}'))
state_code = db.Column(db.Text(), nullable=False)
country_code = db.Column(db.Text(), nullable=False)
leave_date = db.Column(db.DateTime())
first_gen_student = db.Column(db.Boolean())
@staticmethod
def gen_random_id():
print(Student.query.all()) # This errors out.
Here is where I initialize the models:
# Init the DB, create all tables.
db.init_app(app)
from app.models import User, Student
with app.app_context():
db.create_all()
Here is the error stack: Error Stack
When I call the gen_random_id()
function, the error occurs. Any ideas on how to fix?
CodePudding user response:
I ended up figuring out a fix.
If you define your db object as:
db = SQLAlchemy()
then no context is assigned.
If you define your db object as:
db = SQLAlchemy(app)
then it will assign the correct context.