How to get Flask-SQLAlchemy object to load relationship children for Jinja template?

谁说我不能喝 提交于 2019-12-10 04:05:11

问题


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)

I want to do stuff like

{% for user in users %}
    <tr>
        <td>{{ user.id }}</td>
        <td>{{ user.posts|length }}</td>
    </tr>
{% endfor %}

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.

I tried adding .options(joinedload('posts')) to my query, but it said that

InvalidRequestError: 'User.posts' does not support object population - eager loading cannot be applied.

Any help is appreciated.


回答1:


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')



回答2:


It is a query object yes, but those query objects have methods which might help you. Specifically for this use case, you can do:

{% for user in users %}
    <tr>
        <td>{{ user.id }}</td>
        <td>{{ user.posts.count() }}</td>
    </tr>
{% endfor %}



回答3:


You must perform .first() or .all() to your query object to get the actual object/list. e.g
users = User.query.all()



来源:https://stackoverflow.com/questions/22019567/how-to-get-flask-sqlalchemy-object-to-load-relationship-children-for-jinja-templ

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!