环境:MySQL与外键关联,SQLALchemy与Flask关联。
- 表(用户):id,username
-
表(帖子):id,内容
user_id=数据库。列(db.Integer,db.ForeignKey('user.id'))
-
表(注释):id,content,post_author_id
user_id=数据库。列(db.Integer,db.ForeignKey('users.id'))
comment_id=db。列(db.Integer,db.ForeignKey('posts.id'))
当Tom评论Jackie发布的帖子时,比如:
http://myblog.com/post/<postid>
我需要保存这个评论,同时,根据<postid>
,我想将这个帖子的用户id保存为post_author_id到comment表中。这意味着表Comment保存Tom的user_id和Jackie的user_id。如何编写这个SQLALchemy行?
post_author_id = ?
理想情况下,您希望动态获取此信息,而不是将其存储为数据库中的另一列,因为此数据(post_author_id
)已存在于posts
表(Post.user_id)中。
为此,您可以使用SQLAlchemy的混合属性。
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