簡體   English   中英

與棉花糖嵌套Flask-SQLAlchemy關系

[英]Nesting Flask-SQLAlchemy relationship with Marshmallow

我正在使用flask_marshmallow(0.10.1)將來自flask_sqlalchemy表的數據序列化為JSON對象。

但是,這兩個表(發布和評論)之間存在關系。 我已經進行了一些研究,但不確定如何使用嵌套或調用什么來正確序列化為JSON。

這是我的flask_sqlalchemy類:

class Post(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    content = db.Column(db.Text, nullable=False)
    comments = db.relationship('Comment',backref='post_owner') #This needs an integer to increment im

    def __repr__(self):
        return f"Post({self.id}, {self.content}), {self.comments}"

class Comment(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    comment = db.Column(db.Text, nullable=True)
    owner_id = db.Column(db.Integer, db.ForeignKey('post.id'))

    def __repr__(self):
        return f"Comment {self.comment}"

然后是我的flask_marshmallow模式:

class PostSchema(ma.ModelSchema):
    class Meta:
        model = Post

class CommentSchema(ma.ModelSchema):
    class Meta:
        model = Comment

最后,這是我調用架構進行序列化的函數:

def convert_to_json(post_to_convert):  
    post_schema = PostSchema()
    output = post_schema.dump(post_to_convert)
    return output

我得到的當前輸出是這樣的:

{id: 1, content: "Hello Again", comments: Array(3)} comments: (3) [1, 2, 3] 

我想得到的(在評論中:)是這樣的:

{id: 1, content: "Hello Again", comments: Array(3)} comments: (3) ["first comment", "second comment", "third comment"] 

我需要實際的注釋文本數據,而不僅是我得到的ID號。 任何幫助表示贊賞,謝謝。

您可以通過PostSchemaNested字段輕松實現這一PostSchema (假設您正在使用marshmallow-sqlalchemy ):

from marshmallow_sqlalchemy.fields import Nested

class PostSchema(ma.ModelSchema):
    class Meta:
        model = Post
    comments = Nested(CommentSchema, many=True)

class CommentSchema(ma.ModelSchema):
    class Meta:
        model = Comment

我建議您閱讀Marshmallow的有關嵌套模式的文檔,以了解不同的選項和參數。 此外, 棉花糖SQLAlchemy的文檔,尤其是“食譜”部分,將對您有所幫助,並提供有關如何構建模式的想法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM