【发布时间】:2017-01-11 21:06:16
【问题描述】:
我正在尝试连接两个表,以便能够将相应的“主题”与“主题”相关联。连接似乎有效,但模板在渲染时出现此错误:
jinja2.exceptions.UndefinedError: 'sqlalchemy.util._collections.result object'没有属性'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>
【问题讨论】:
标签: flask jinja2 flask-sqlalchemy