环境:具有外键关联的MySQL,以及带有Flask的SQLALchemy。
表(帖子):id,content
user_id = db.Column(db.Integer,db.ForeignKey('user.id'))
表(评论):id,content,post_author_id
user_id = db.Column(db.Integer,db.ForeignKey('users.id'))
comment_id = db.Column(db.Integer,db.ForeignKey('posts.id'))
当Tom对Jackie发表的帖子发表评论时,就像这样:
http://myblog.com/post/<postid>
我需要保存此评论,同时,根据<postid>
,我想将此帖子的用户ID保存为post_author_id到表评论中。这意味着表评论保存了Tom的user_id和Jackie的user_id。如何编写这个SQLALchemy行?
post_author_id = ?
答案 0 :(得分:1)
理想情况下,您希望动态获取此信息,而不是将其存储为数据库中的另一列,因为此数据(post_author_id
)已存在于posts
表中(Post.user_id)。 / p>
为此,您可以使用SQLAlchemy的Hybrid Attributes。
from sqlalchemy import Column, Integer, String, ForeignKey
from sqlalchemy.orm import relationship
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.ext.hybrid import hybrid_property
Base = declarative_base()
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
username = Column(String, nullable=False)
class Post(Base):
__tablename__ = 'posts'
id = Column(Integer, primary_key=True)
user_id = Column(Integer, ForeignKey('users.id'))
user = relationship(User)
content = Column(String)
class Comment(Base):
__tablename__ = 'comments'
id = Column(Integer, primary_key=True)
user_id = Column(Integer, ForeignKey('users.id'))
post_id = Column(Integer, ForeignKey('posts.id'))
post = relationship(Post)
content = Column(String)
@hybrid_property
def post_author_id(self):
return self.post.user_id
您可以通过多种方式撰写Comment.post_author_id