尝试通过以下方式使用SQLAlchemy在SqlLiteDb中插入新记录:
user_1=User(username='First User',userEmail='first@email.com',password='password')
我遇到以下错误:
sqlalchemy.exc.InvalidRequestError: One or more mappers failed to initialize - can't proceed with initialization of other mappers. Triggering mapper: 'mapped class User->user'. Original exception was: When initializing mapper mapped class User->user, expression 'Post' failed to locate a name ('Post'). If this is a class name, consider adding this relationship() to the <class 'flaskblog.User'> class after both dependent classes have been defined.
class User(flaskDb.Model):
id = flaskDb.Column(flaskDb.Integer, primary_key=True)
username = flaskDb.Column(flaskDb.String(20), unique=True, nullable=False)
userEmail = flaskDb.Column(flaskDb.String(
120), unique=True, nullable=False)
password = flaskDb.Column(flaskDb.String(20), nullable=False)
image_file = flaskDb.Column(flaskDb.String(
20), nullable=False, default="default.jpg")
posts = flaskDb.relationship('Post', backref="author", lazy=True)
def __repr__(self):
return f"User('{self.username}','{self.userEmail}','{self.image_file}')"
class Post(flaskDb.Model):
id = flaskDb.Column(flaskDb.Integer, primary_key=True, nullable=False)
title = flaskDb.Column(flaskDb.String(25), nullable=False)
content = flaskDb.Column(flaskDb.Text, nullable=False)
datePosted = flaskDb.Column(
flaskDb.DateTime, nullable=False, default=datetime.utcnow)
user_id = flaskDb.Column(
flaskDb.Integer, flaskDb.ForeignKey('user.id'), nullable=False)
def __repr__(self):
return f"Post('{self.title}','{self.datePosted}','{self.title}')"
有人可以帮我吗? TIA!
答案 0 :(得分:0)
您遇到了循环依赖性错误。
而不是将帖子放置在Sser中。
posts = flaskDb.relationship('Post', backref="author", lazy=True)
将其删除并将其放在“帖子”上。
user = flaskDb.relationship('User', backref="posts", lazy=True)
您仍然可以通过以下方式访问用户:
usera = User.query.get(1)
usera.posts