简体   繁体   English

使用flask-sqlalchemy访问相关记录

[英]Access related records using flask-sqlalchemy

I am trying to access all related records using flask-sqlalchemy. 我正在尝试使用flask-sqlalchemy访问所有相关记录。

My model class' have the following structure: 我的模型类具有以下结构:

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64), index=True, nullable=False)
    posts = db.relationship('Post', backref='author', lazy='dynamic')

    def __repr__(self):
        return f'<User {self.name}>'


class Post(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(64), index=True, nullable=False)
    date_posted = db.Column(db.DateTime, index=True, default=datetime.utcnow)
    department_id = db.Column(db.Integer, db.ForeignKey('user.id'))

    def __repr__(self):
        return f'<Post {self.title}>'

I would like to access Post information related to a particular User; 我想访问与特定用户相关的帖子信息; The following template is passed a copy of the Users record. 下面的模板传递了用户记录的副本。

{% if users %}
<p>USERS</p>
    <ul>
        {% for user in users %}
            <li> {{ user.id }}</li>
            <li> {{ user.name }}</li>

        {% for post in user.posts %}
            <li>{{ post.title }} </li>
        {% endfor %}

        {% endfor %}
    </ul>
{% endif %}

Do I need to create some kind of dict to map posts to their uers before passing the values to the template? 在将值传递到模板之前,我是否需要创建某种类型的词典以将帖子映射到其用户?

I appreciate the simplicity of this question, I am an absolute beginner. 我很欣赏这个问题的简单性,我是一个绝对的初学者。 Any help would be very much appreciated. 任何帮助将不胜感激。

What is in your template looks right, you now just need to pass the users to the template. 模板中的内容看起来正确,现在您只需要将用户传递给模板即可。

@app.route('/posts', methods=['GET'])
def posts():
    users = User.query.all()
    return render_template('your_template.html', users=users)

so now your {%for user in users%} in the template refers to the queried users with the loaded relationships (hoping you have your models.py, your app.py (where the above code is) with the relevant imports and template). 因此,现在您的模板中的{%for users in users%}用户是指已加载关系的查询用户(希望您拥有您的models.py,app.py(包含上面的代码)以及相关的导入和模板) 。

hope that helps 希望能有所帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM