如何解决此烧瓶sqlalchemy错误“ sqlalchemy.exc.InvalidRequestError”?

时间:2020-07-02 08:43:44

标签: flask sqlalchemy flask-sqlalchemy

from datetime import datetime
from pack import db,login_manager
from flask_login import UserMixin

# SQLALCHEMY_TRACK_MODIFICATIONS = False

@login_manager.user_loader
def load_user(user_id):
    return User.query.get(int(user_id))

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(20), unique = True, nullable = False)
    email = db.Column(db.String(150), unique = True, nullable = False)
    password = db.Column(db.String(60), nullable = False)
    profile_pic = db.Column(db.String(20), nullable = False, default = "default_profile_pic.jpg")
    posts = db.relationship('Post', backref = 'author', lazy = True)
    comments = db.relationship('Comment', backref = 'commentor', lazy = True)


    def __repr__(self):
        return f"User('{self.username}','{self.email}','{self.profile_pic}')"
    
class Post(db.Model,UserMixin):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(100), nullable = False)
    date_posted = db.Column(db.DateTime, nullable = False, default = datetime.utcnow)
    content = db.Column(db.Text, nullable = False)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable = False)
    post_comments = db.relationship('Comment', backref = 'commentor', lazy = 'dynamic')

    def __repr__(self):
        return f"Post('{self.title}','{self.content}','{self.date_posted}','{self.comments}')"

class Comment(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    comment = db.Column(db.String(100000), nullable = False)
    timestamp = db.Column(db.DateTime, nullable = False, default = datetime.utcnow, index = True)
    user_comment_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable = False)
    post_comment_id = db.Column(db.Integer, db.ForeignKey('post.id'))

    def __repr__(self):
        return f"Post('{self.comment}','{self.user_comment_id}','{self.post_comment_id}')"

这会导致此错误:

sqlalchemy.exc.InvalidRequestError: One or more mappers failed to initialize - can't proceed with initialization of other mappers. Triggering mapper: 'mapped class Post->post'. Original exception was: Error creating backref 'commentor' on relationship 'Post.post_comments': property of that name exists on mapper 'mapped class Comment->comment'

请帮助我解决此错误。我想添加一个功能以评论帖子,为此,我试图将 Comment 模型与 Post User 模型连接。 / p>

1 个答案:

答案 0 :(得分:0)

在错误中,您有:Post.post_comments': property of that name exists on mapper 'mapped class Comment->comment

似乎在User中,您有comments在注释中创建了一个后向引用'commentor',在Post中,您还有post_comments也创建了一个后向引用{ {1}}在评论中。

例如,在'commentor'中,您可以将Post更改为:

post_comment

编辑: 使用backref参数定义一对多关系时,不需要post_comments = db.relationship('Comment', backref = 'post_commented', lazy = 'dynamic') (在Post中),user_id(在user_comment_id中),Comment(在{{1 }}):只需将其删除。

您应该再看看https://docs.sqlalchemy.org/en/13/orm/basic_relationships.html#one-to-many(后向引用部分)