我在Jinja模板页面中无法正确显示SQLAlchemy查询的结果。
我的项目基于一级方程式车手和他们所驾驶的车队。我有一个页面,列出了F1中的车队,并且应该列出每个车队参赛的车手(车手和车队之间的多对多关系)。
我收到的输出是正确的,但是它似乎在列表类型的输出中分组在一起。我希望每个团队的驱动程序都以字符串的形式单独列出,而不是分组在一起的列表。
这是我的代码:
models.py
from datetime import datetime
from app import db
class Team_driver(db.Model):
# Many-to-many relationship table between Driver and Team
__tablename__ = "team_driver"
id = db.Column(db.Integer, primary_key=True)
team_id = db.Column(db.Integer, db.ForeignKey('team.id'), nullable=False)
driver_id = db.Column(db.Integer, db.ForeignKey('driver.id'), nullable=False)
class Team(db.Model):
__tablename__ = "team"
id = db.Column(db.Integer, primary_key=True)
teamName = db.Column(db.String(64))
nationality = db.Column(db.String(64))
# relationship between Team table and Driver table, reference 'team' in forms
drivers = db.relationship('Driver', secondary="team_driver", backref='team')
def __repr__(self):
# specify variables to return to web page from backref
return '{}'.format(self.teamName)
class Driver(db.Model):
__tablename__ = "driver"
id = db.Column(db.Integer, primary_key=True)
firstName = db.Column(db.String(64))
lastName = db.Column(db.String(64))
raceNum = db.Column(db.Integer)
nationality = db.Column(db.String(64))
# relationship between Driver table and Team table, reference 'driver' in forms
teams = db.relationship('Team', secondary="team_driver", backref='driver')
def __repr__(self):
# specify variables to return to web page from backref
return '{} {}'.format(self.firstName,self.lastName)
routes.py(仅适用于特定路由)
@app.route('/teamDetails', methods=['GET', 'POST'])
def teamDetails():
details = Team.query.all()
return render_template('teamDetails.html', title='Team Details', details=details)
driverDetails.html
<!-- teamDetails.html -->
<!-- all other html files must now extend index.html and not base.html -->
{% extends "index.html" %}
{% block content %}
<h1>Team Details</h1>
{% for d in details %}
<div><p>Team Name: {{ d.teamName }}<br>Nationality: {{ d.nationality }}
<br>Drivers: {{ d.driver }}</p></div>
{% endfor %}
{% endblock %}
这是我从网页上获得的输出
我想要的是显示相关驱动程序的页面,但要单独显示,没有[]括号。
任何人都可以帮助我解决问题吗?
非常感谢。
答案 0 :(得分:0)
由于d.driver
是驱动程序列表,因此您应该分别打印列表的每个项目,因为如果您打印某些内容的列表,那么它还将包括方括号。
{% block content %}
<h1>Team Details</h1>
{% for d in details %}
<div><p>Team Name: {{ d.teamName }}<br>Nationality: {{ d.nationality }}
<br>Drivers:
{% for driver in d.drivers %}
{{ driver }}
{% endfor %}
</p></div>
{% endfor %}
{% endblock %}