I have a example about one-to-many relationship in Flask-SQLAlchemy:
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(80))
email = db.Column(db.String(120), unique=True)
posts = db.relationship('Post', backref='user')
class Post(db.Model):
id = db.Column(db.Integer, primary_key=True)
content = db.Column(db.Text)
user_id = db.Column(db.Integer, db.ForeignKey('user.id')
According to Declaring Models , I can get list of posts of User U
by U.posts
. But in constrast, how can I get author's name of Post P
as an attribute like P.author_name
, instead of P.user.name
?
尝试P.user
,根据您在 backref 中定义的内容
I can modify the Post
class by:
class Post(db.Model):
id = db.Column(db.Integer, primary_key=True)
content = db.Column(db.Text)
user_id = db.Column(db.Integer, db.ForeignKey('user.id')
@cached_property
def author_name(self):
return self.user.name
then, it will see P.author_name
as P.user.name
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.