如何更新 Flask-SQLAlchemy-Marshmallow 中的嵌套对象

问题描述 投票:0回答:1

你能帮我更新 Flask-SQLAlchemy-Marshmallow 中的嵌套对象吗?这是模型

父模型

class ParentModel(db.Model):
    __tablename__ = "parent"

    id = db.Column(db.Integer, primary_key=True)
    parent_name = db.Column(db.String(100), nullable=False)
    
    childrens = db.relationship("ChildrensModel",  cascade="all,delete", backref='parent')

    @classmethod
    def find_by_id(cls, _id: int) -> "ParentModel":
        return cls.query.filter_by(id=_id).first()

    @classmethod
    def find_by_name(cls, name: int) -> "ParentModel":
        return cls.query.filter_by(parent_name=name).first()

    @classmethod
    def find_all(cls) -> List["ParentModel"]:
        return cls.query.all()

    def save_to_db(self) -> None:
        db.session.add(self)
        db.session.commit()

    def delete_from_db(self) -> None:
        db.session.delete(self)
        db.session.commit()

儿童模型

class ChildrenModel(db.Model):
    __tablename__ = "children"

    id = db.Column(db.Integer, primary_key=True)
    children_name = db.Column(db.String(100), nullable=False)
    parent_id = db.Column(db.Integer,db.ForeignKey("parent.id") primary_key=True)

    @classmethod
    def find_by_id(cls, _id: int) -> "ChildrenModel":
        return cls.query.filter_by(id=_id).first()

    @classmethod
    def find_by_name(cls, name: int) -> "ChildrenModel":
        return cls.query.filter_by(children_name=name).first()

    @classmethod
    def find_all(cls) -> List["ChildrenModel"]:
        return cls.query.all()

    def save_to_db(self) -> None:
        db.session.add(self)
        db.session.commit()

    def delete_from_db(self) -> None:
        db.session.delete(self)
        db.session.commit()

儿童架构

class ChildrenSchema(ma.ModelSchema):


    class Meta:
        model = ChildrenModel
        include_fk = True

父架构

class ParentSchema(ma.ModelSchema):

    children= fields.List(fields.Nested(ChildrenSchema(dump_only=("parent_id",))),required=True)

    class Meta:
        model = ParentModel
        include_fk = True

这是所需的 JSON 格式。您能否告诉我如何以以下格式更新现有的嵌套对象。

{
  "parent_name":"parent1",
  "children":[{"children_name":"children_1"},{"children_name":"children_2"}]
}

谢谢大家抽出宝贵的时间。

python-3.x flask flask-sqlalchemy flask-restful flask-marshmallow
1个回答
0
投票

嵌套架构规范必须列出要包含或排除的字段。这个配置:

from flask_marshmallow import Marshmallow
from marshmallow_sqlalchemy.fields import Nested

...

class ChildrenSchema(ma.SQLAlchemySchema):
    class Meta:
        model = ChildrenModel
        include_fk = False

    id = ma.auto_field()
    parent_id = ma.auto_field()
    children_name = ma.auto_field()


class ParentSchema(ma.SQLAlchemySchema):

    class Meta:
        model = ParentModel

    parent_name = ma.auto_field()
    children = Nested(
        ChildrenSchema, attribute='childrens',many=True, only=('children_name',)
    )

会生成如下输出:

{'parent_name': 'p1', 'children': [{'children_name': 'c1'}, {'children_name': 'c2'}]}

使用这些包在 Python3.12 上进行测试:

flask-marshmallow      1.2.1
Flask-SQLAlchemy       3.1.1
marshmallow            3.21.3
marshmallow-sqlalchemy 1.0.0
SQLAlchemy             2.0.31
© www.soinside.com 2019 - 2024. All rights reserved.