How can I get information from 2 separate tables with a single request in Flask?

折月煮酒 提交于 2021-02-08 11:26:30

问题


class posts(db.Model):
    __tablename__ = "posts"
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100))
    postName = db.Column(db.String(100))
    postDescription = db.Column(db.String(500))
    postLike = db.Column(db.Integer)

class postComment(db.Model):
    __tablename__ = "postComment"
    id = db.Column(db.Integer, primary_key=True)
    postID = db.Column(db.Integer)
    senderName = db.Column(db.String(20))
    commentPost = db.Column(db.String(300))

class PostsSchema(ma.Schema):
    class Meta:
        fields = ('id', 'name', 'postName', 'postDescription', 'postLike')

class CommentsSchema(ma.Schema):
    class Meta:
        fields = ('id', 'postID', 'senderName', 'commentPost')

posts_schema = PostsSchema()
posts_schema2 = PostsSchema(many=True)

comments_schema = CommentsSchema()
comments_schema2 = CommentsSchema(many=True)

I get this according to the id in the post table.

{"id":2,"name":"bahadir","postDescription":"descript","postLike":12,"postName":"slsl"}

and I get this according to the id in the comments Table.

{"commentPost":"merhaba ben burak","id":2,"postID":2,"senderName":"burak"}

Whenever I give the id I want to get the post first, then the postComment as above. (The postID is associated with the ID.)

    @app.route('/posts/<id>', methods=['GET'])
    def get_posts_id(id):
    
        #post = posts.query.get(id)
        comments = postComment.query.get(id)
    
        # I want to do this -> comments_schema + posts_schema . jsonify(post,comments)
#HOW CAN I DO
        return comments_schema.jsonify(comments)

The data I want to come is this:

    [[{"id":2,"name":"bahadir","postDescription":"descript","postLike":12,"postName":"slsl"}]
[{"commentPost":"merhaba ben burak","id":1,"postID":2,"senderName":"burak"},{"commentPost":"hello flask tryyyy","id":2,"postID":2,"senderName":"hello"}]]

postID = id

来源:https://stackoverflow.com/questions/65409817/how-can-i-get-information-from-2-separate-tables-with-a-single-request-in-flask

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!