flask-sqlachemary 使用 backref需要使用全路径?

新手上路,请多包涵

尝试创建 model.py 时使用 'backref' 参数出现

sqlalchemy.exc.ArgumentError: Error creating backref 'user' on relationship 'User.to_blog': property of that name exists on mapper 'mapped class Blog->blog'

代码如下

from app import db
from datetime import datetime


class User(db.Model):
    __tablename__ = "user"
    __table_args__ = {"extend_existing": True}
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    name = db.Column(db.String(255), unique=True, nullable=False)
    pwd = db.Column(db.String(255), nullable=False)
    email = db.Column(db.String(255))
    introduce = db.Column(db.Text, default="xxx")
    headName = db.Column(db.String(255), default='default.png')
    head = db.Column(db.LargeBinary(1048576))
    right = db.Column(db.Integer, default=2)

    # backref
    to_blog = db.relationship('Blog', backref='user')    # error



    def __repr__(self):
        return "User:%s %s %s" % (self.name, self.pwd, self.id)

    


class Blog(db.Model):
    __tablename__ = "blog"
    __table_args__ = {"extend_existing": True}
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    content = db.Column(db.Text)
    body_html = db.Column(db.Text)
    title = db.Column(db.String(255), nullable=False, unique=True)
    headName = db.Column(db.String(255), default='default_blog.png')
    head = db.Column(db.LargeBinary(1048576))

    # ForeignKey
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
    
    
    
if __name__ == "__main__":
    db.drop_all()
    db.create_all()
    # #
    roles = User(id=2, name='cat', pwd='cat', email='cat@qq.com')
    db.session.add(roles)
    db.session.commit()
 

报错如下

sqlalchemy.exc.InvalidRequestError: Multiple classes found for path "Blog" in the registry of this declarative base. Please use a fully module-qualified path.

我尝试将代码修改为以下才解决问题,此程序曾经能够稳定运行(未修改前)

    to_blog = db.relationship('app.models.Blog', backref='user') 

这是为什么呢?版本问题吗

回复
阅读 505
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏