gpt4 book ai didi

python - 评论帖子时如何通过postid获取帖子的用户id?

转载 作者:行者123 更新时间:2023-11-28 23:39:54 25 4
gpt4 key购买 nike

环境:带有外键关联的 MySQL 和带有 Flask 的 SQLALchemy。

  • 表(用户):id,用户名
  • 表(帖子):id、内容

    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 保存到表 Comment 中。这意味着表 Comment 保存了 Tom 的 user_id 和 Jackie 的 user_id。如何编写此 SQLALchemy 行?

post_author_id = ?

最佳答案

理想情况下,您希望动态获取此信息而不是将其作为另一列存储在数据库中,因为此数据 (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

关于python - 评论帖子时如何通过postid获取帖子的用户id?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34695608/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com