2

你能帮我更新 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"}]
}

伙计们,谢谢你的时间。

4

0 回答 0