遍历SQLAlchemy关系-TypeError和backref问题

时间:2019-06-28 00:20:51

标签: python flask flask-sqlalchemy

尝试在我的flask应用程序中创建帖子后,此错误消息显示TypeError: 'author' is an invalid keyword argument for Post

这是我的models.py中的以下代码:

class User(db.Model, UserMixin):
    id = db.Column(db.Integer, primary_key=True)
    posts = db.relationship('Post', backref='author', lazy=True)
    colleges_accepted = db.relationship('CollegesAccepted', backref='author', lazy=True)
    posts = db.relationship('Post', primaryjoin="User.id==Post.author_id")
    ...

class Post(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    author_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
    ...

class CollegesAccepted(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
    ...

这是route.py的代码:

@app.route("/post/new", methods=['GET', 'POST'])
@login_required
def new_post():
    form = PostForm()
    if form.validate_on_submit():
        post = Post(title=form.title.data,
                    content=form.content.data,
                    author=current_user,
                    college_attending=current_user.college_attending)
        db.session.add(post)
        db.session.commit()
        flash('Your post has been created!', 'success')
        return redirect(url_for('home'))
    return render_template('create_post.html', title='New Post', form=form)

但是,这并不能达到预期的效果-在显示帖子时,我想显示作者/用户的属性以及帖子的内容。我想使用我在models.py中定义的关系,以便能够在html / jinja2模板中执行以下操作:

{% for college in post.author.colleges_accepted_to %}
    {{ college }}
{% endfor %}

1 个答案:

答案 0 :(得分:0)

您已经在colleges_accepted关系上设置了backref,但是没有在posts关系上设置了backref。因此,您的post对象不知道如何获取其author

另外,您声明colleges_accepted,然后在模板中使用colleges_accepted_to