1
我試圖加入兩個表,能夠將相應的「主題」與「主題」相關聯。加入似乎工作,但模板渲染時出現此錯誤:加入表丟失「ID」屬性
jinja2.exceptions.UndefinedError: 'sqlalchemy.util._collections.result object' has no attribute 'id'
如何在加入表後處理Topic.id?
車型
class Topic(db.Model):
id = db.Column(db.Integer, primary_key=True)
topic_name = db.Column(db.String(64))
opinions = db.relationship(Opinion, backref='topic')
theme_id = db.Column(db.Integer, db.ForeignKey('theme.id'))
class Theme(db.Model):
id = db.Column(db.Integer, primary_key=True)
theme_name = db.Column(db.String(64))
topics = db.relationship(Topic, backref='theme')
視圖
@main.route('/topics', methods=['GET', 'POST'])
def topics():
topics = db.session.query(Topic, Theme).join(Theme).order_by(Theme.theme_name).all()
themes = Theme.query
form = TopicForm()
form.theme.choices = [(t.id, t.theme_name) for t in Theme.query.order_by('theme_name')]
if form.validate_on_submit():
topic = Topic(topic_name=form.topic_name.data,
theme_id=form.theme.data)
db.session.add(topic)
return render_template('topics.html', topics=topics, themes=themes, form=form)
HTML模板的Jinja2
<table class="table table-hover parties">
<thead><tr><th>Theme</th><th>#</th><th>Name</th><th>Delete</th></tr></thead>
{% for topic in topics %}
<tr>
<td><a href="#">{{ topic.theme_id }}</a></td>
<td><a href="#">{{ topic.id }}</a></td>
<td><a href="#">{{ topic.topic_name }}<span class="badge">0</span></a></td>
<td><a class="btn btn-danger btn-xs" href="{{ url_for('main.delete_topic', id=topic.id) }}" role="button">Delete</a></td>
</tr>
{% endfor %}
</table>
謝謝,這是一個快速解決方案。兩種實現明顯不同。 –