2016-01-09 244 views
1

环境:具有外键关联的MySQL和具有Flask的SQLALchemy。如何在评论帖子时通过postid获取其帖子的用户ID?

  • 表(用户):ID,用户名
  • 表(POST):ID,内容

    USER_ID = db.Column(db.Integer,db.ForeignKey( 'user.id') )

  • 表(注释):ID,内容,post_author_id

    USER_ID = db.Column(db.Integer,db.ForeignKey( 'users.id'))

    COMMENT_ID = db.Column(db.Integer,db.ForeignKey( 'posts.id'))

当Tom由成龙公布的信息发表评论,就像这样:

http://myblog.com/post/<postid> 

我需要保存此评论,同时,根据<postid>,我想将此帖子的用户ID保存为post_author_id到表Comment中。这意味着table Comment保存了Tom的user_id和Jackie的user_id。如何编写这个SQLALchemy行?

post_author_id = ? 

回答

1

理想情况下,你想获得这些信息动态,而不是因为这个数据(post_author_id)您posts表(Post.user_id)中已存在将其存储在数据库中的另一列。

为此,您可以使用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