我正在尝试使用 sqlalchemy 加载策略来加快查询速度。读完这篇文章后,我意识到我犯了循环遍历模板中的记录的错误。唯一的问题是我收到此错误:
NameError:未定义全局名称“joinedload”。
发生这种情况是因为我使用的是 flask-sqlalchemy 还是我忘记导入某些东西?
模型.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)
违规蓝图:
@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)
模板:
{% 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 %}
为了给我的模型一些背景信息,我有一个检查记录。每次检查都有一个或多个违规行为。而且每次违规都有多次检查