Wilberto
Wilberto

Reputation: 540

Error flask-sqlalchemy NameError: global name 'joinedload' is not defined

I'm trying to use a sqlalchemy loading strategy to speed up my queries. After reading this I realized that I was making the mistake of looping through the records in my template. The only problem is that i get this error:

NameError: global name 'joinedload' is not defined.

Is this happening because I'm using flask-sqlalchemy or em I forgetting to import something?

Models.py:

inspection_violations = db.Table('inspection_violations',
db.Column('violation_id', db.Integer, db.ForeignKey('violations.violation_number')),
db.Column('inspection_id', db.Integer, db.ForeignKey('inspection.inspection_id')), )

class Inspection(db.Model):
    inspection_id = db.Column(db.Integer, primary_key=True)
    violations = db.relationship('Violations', secondary=inspection_violations, backref=db.backref('inspection', lazy='dinamic'))
    facility_id = db.Column(db.String(100), db.ForeignKey('facilities.branch_name'))

class Violations(db.Model):
    violation_number = db.Column(db.Integer, primary_key=True)
    details  = db.Column(db.Text)

Violation Blueprint:

@violations_blueprint.route('/violations/<int:violation_number>')
def show_single_violation(violation_number):
    violation = Violations.query.options(joinedload('inspection')).get(violation_number)
    return render_template('violations/single-violation.html' ,violation=violation)

Template:

{% for inspection in violation.inspection %} 
  <p><a href="{{ url_for('inspection_blueprint.show_inspection', id=inspection.inspection_id) }}">    {{ inspection.facilities.branch_name }}</a></p>
{% endfor %}

To give some context to my models I have a inspection record. Every inspection has one or more violations. And every violation has many inspections

Upvotes: 10

Views: 9096

Answers (2)

user4985526
user4985526

Reputation:

On my condition, it's just a order problem

class Inspection(db.Model):

class Violations(db.Model):

inspection_violations = ()     //wrong junction table position 

this will not work too.because when you use inspection_violations it's not defined yet. and will also report the same problem

simply change the order will make it work

inspection_violations = ()   //right junction table position

class Inspection(db.Model):

class Violations(db.Model):

this is the right way to do this.

Upvotes: 0

Bibhas Debnath
Bibhas Debnath

Reputation: 14939

Well, the error message says joinedload is not defined, so the obvious solution would be to check if you imported it and if not -

from sqlalchemy.orm import joinedload

Upvotes: 21

Related Questions