模型中的代码如下
class User(db.Model):
id = db.Column(db.Integer,primary_key = True)
nickname = db.Column(db.String(64),index = True,unique = True)
email = db.Column(db.String(120),index = True,unique= True)
posts = db.relationship('Post',backref = 'author' , lazy = 'dynamic')
def __repr__(self):
return '<User %r>' % (self.nickname)
class Post(db.Model):
id = db.Column(db.Integer,primary_key = True)
body = db.Column(db.String(140))
timestamp = db.Column(db.DateTime)
user_id = db.Column(db.Integer,db.ForeignKey('user.id'))
def __repr__(self):
return '<Post %r>' % (self.body)
然后使用迁移将模型同步到数据库。 但是数据库中的 post 表不会生成指向 user 表的外键。
答案 0 :(得分:0)
post_id = db.Column(db.Integer)
relationship(
"Post",
foreign_keys=[post_id],
primaryjoin="User.post_id == Post.id",
backref=backref("author", lazy="dynamic")
)