sqlite 尝试在两个flask_sqlalchemy表之间创建一对多关系时出错:sqlalchemy.exc.InvalidRequestError

7y4bm7vi  于 2023-05-18  发布在  SQLite
关注(0)|答案(1)|浏览(210)

我试图在BlogPost表和用户表之间创建一个关系。每次我尝试运行程序时,都会收到此错误:

sqlalchemy.exc.InvalidRequestError: back_populates on relationship 'Users.posts' refers to attribute 'BlogPost.author' that is not a relationship.  The back_populates parameter should refer to the name of a relationship on the target class.

下面是我的代码:

##CONFIGURE TABLE
class Users(UserMixin, db.Model):
    __tablename__ = 'users'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(255), nullable=False)
    email = db.Column(db.String(255), nullable=False, unique=True)
    password = db.Column(db.String(255), nullable=False)
    posts = db.relationship("BlogPost", back_populates="author")

##CONFIGURE TABLE
class BlogPost(db.Model):
    __tablename__ = 'blog_post'
    id = db.Column(db.Integer, primary_key=True)
    author_id = db.Column(db.Integer, db.ForeignKey("users.id"), nullable=False)
    author = db.relationship("Users", back_populates="posts") # lazy='dynamic'
    title = db.Column(db.String(250), unique=True, nullable=False)
    subtitle = db.Column(db.String(250), nullable=False)
    date = db.Column(db.String(250), nullable=False)
    body = db.Column(db.Text, nullable=False)
    author = db.Column(db.String(250), nullable=False)
    img_url = db.Column(db.String(250), nullable=False)

with app.app_context():
    db.create_all()

我已经回到这个问题上,仍然无法找出是什么导致了错误。

deyfvvtc

deyfvvtc1#

下面是正确的代码:

class Users(UserMixin, db.Model):
    __tablename__ = 'users'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(255), nullable=False)
    email = db.Column(db.String(255), nullable=False, unique=True)
    password = db.Column(db.String(255), nullable=False)
    posts = db.relationship("BlogPost", back_populates="author")

class BlogPost(db.Model):
    __tablename__ = 'blog_post'
    id = db.Column(db.Integer, primary_key=True)
    author_id = db.Column(db.Integer, db.ForeignKey("users.id"), nullable=False)
    author = db.relationship(Users, back_populates="posts")
    title = db.Column(db.String(250), unique=True, nullable=False)
    subtitle = db.Column(db.String(250), nullable=False)
    date = db.Column(db.String(250), nullable=False)
    body = db.Column(db.Text, nullable=False)
    img_url = db.Column(db.String(250), nullable=False)

相关问题