在试图创建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)
# 反向引用
to_blog = db.relationship('app.models.Blog', backref='user')
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))
# 外键
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()
原本为:
to_blog = db.relationship('Blog', backref='user')
因为报错
sqlalchemy.exc.InvalidRequestError: Multiple classes found for path "Blog" in the registry of this declarative base. Please use a fully module-qualified path.
才改成前者