问题描述
我有User和Post的基本模型.在我的用户模型中,我有
I have basic models for User and Post. In my User model, I have
posts = db.relationship('Post', backref='user', lazy='dynamic')
但是,当我做类似的事情
However, when I do something like
return render_template('user.html', users=users)
我想做类似的事情
{% for user in users %}
<tr>
<td>{{ user.id }}</td>
<td>{{ user.posts|length }}</td>
</tr>
{% endfor %}
不幸的是,这不起作用.帖子是查询,而不是lazy='dynamic'
的对象b/c.如果更改lazy='joined'
,我可以执行上述操作,但是无论何时我查询用户,它将为用户加载所有帖子.
Unfortunately, this doesn't work. Posts is a query, not an object b/c of lazy='dynamic'
. I can do the above if I change lazy='joined'
, but then it would be loading all posts for users anytime I query for a User.
我尝试在查询中添加.options(joinedload('posts'))
,但它表示
I tried adding .options(joinedload('posts'))
to my query, but it said that
感谢您的帮助.
推荐答案
只需删除lazy="dynamic"
参数,您就可以使用joinedload
而不会出现问题. (请记住,执行此操作时会遇到难以诊断的N + 1查询问题.如果始终需要这些帖子,请改用joined
).
Simply remove the lazy="dynamic"
argument and you will be able to use a joinedload
without issues. (Remember, when you do this you open yourself up to hard-to-diagnose N+1 query issues. If you will always need the posts, use joined
instead).
如果您需要所有行为(可查询,可连接和延迟加载),建议您查看,建议为动态查询添加另一个属性:
If you need all behaviors (queriable, joinable, and lazy-loaded), I suggest looking at the answer to this question, which suggests adding another attribute for dynamic queries:
class User(db.Model):
posts = db.relationship('Post', backref='user')
class Post(db.Model):
# etc.
User.posts_query = db.relationship(Post, lazy='dynamic')
这篇关于如何获得Flask-SQLAlchemy对象为Jinja模板加载关系子级?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!