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?

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:

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


{% 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

5/28/2013 10:19:53 PM

Accepted Answer

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
5/28/2013 10:22:59 PM

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow