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

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.jpg')

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.jpg')

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') 

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

以上是 flask-sqlachemary 使用 backref需要使用全路径? 的全部内容, 来源链接: utcz.com/p/938362.html

回到顶部