Flask棉花糖系列化与外场多对多关系

2024-06-02 17:33:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我在使用序列化模型对象的Flask应用程序中遇到了一个问题,该对象与存储在关联表中的额外字段有多对多的关系。我想要一个序列化的数据,如下所示:

{
    "id": "123",
    "name": "name",
    "mobile": "phone number",
    "interest": [1, 2, 3]
    "_embedded": {
        "interest": [
            {
                "id": 1,
                "name": "ECONOMIC",
                "active": true,
            },
            {
                "id": 2,
                "name": "POETRY",
                "active": true,
            },
            {
                "id": 3,
                "name": "SPORT",
                "active": false,
            },
        ]
    }
}

现在需要准备以下模型:

^{pr2}$

但现在我在想办法,如何用marshullow模式准备sqlalchemy查询。有什么想法吗?在

编辑:

我目前的棉花糖模式是:

class InterestSchema(ma.ModelSchema):
    class Meta:
        model = Interests
        exclude = ('owners',)


class OwnerSchema(ma.ModelSchema):
    interests = ma.Nested(InterestSchema, many=True)

    class Meta:
        model = Owners

Tags: 对象name模型idtruemodel序列化模式
1条回答
网友
1楼 · 发布于 2024-06-02 17:33:09

此模式提供了与您的规范非常相似的内容:

from marshmallow import Schema, fields


class InterestSchema(Schema):
    class Meta:
        fields = ('id', 'name')
        ordered = True


class OwnerInterestSchema(Schema):
    interest = fields.Nested(InterestSchema)

    class Meta:
        fields = ('id', 'interest', 'active')
        ordered = True


class OwnerSchema(Schema):
    interests = fields.Nested(OwnerInterestSchema, many=True)

    class Meta:
        fields = ('id', 'name', 'mobile', 'interests')
        ordered = True

然后,您可以像这样序列化您的数据(请注意,我的模型与您的模型的名称不完全相同):

^{pr2}$

让我缩进输出,这样您就可以看到发生了什么:

{
  "id": 1,
  "name": "John",
  "mobile": "07123456789",
  "interests": [
    {
      "interest": {
        "id": 1,
        "name": "Economics"
      },
      "active": true
    },
    {
      "interest": {
        "id": 2,
        "name": "Poetry"
      },
      "active": true
    },
    {
      "interest": {
        "id": 3,
        "name": "Sport"
      },
      "active": false
    }
  ]
}

如果需要的话,您可以调整它以使用model plus exclude范式。如果您真的希望在JSON中使用"_embedded"字段,那么您可能需要一个自定义字段,如here所述。在

您还可以使用自定义字段来简化您的兴趣,并将"active"字段与"id"和{}放在同一级别,但我认为这会误导您。在

相关问题 更多 >