我正在尝试加入两个表,以便能够将相应的“主题”与“主题”相关联。连接似乎有效,但模板在渲染时会出现此错误:
jinja2.exceptions.UndefinedError:'sqlalchemy.util._collections.result 对象'没有属性'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>
答案 0 :(得分:3)
将您的查询更改为:
topics = db.session.query(Topic).join(Theme).order_by(Theme.theme_name).all()
使用query(Topic)
表示我们有兴趣获取Topic
值。相比之下,您当前的实现使用query(Topic, Theme)
表示您有兴趣获取(Topic, Theme)
的元组。