python - Flask Marshmallow 使用额外字段序列化多对多关系

标签 python flask serialization sqlalchemy marshmallow

我在具有序列化模型对象的 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,
            },
        ]
    }
}

现在我设法准备了必要的模型如下:

class OwnerInterests(db.Model):
    owner_id = db.Column(db.Integer, db.ForeignKey('owners.id'), primary_key=True)
    interest_id = db.Column(db.Integer, db.ForeignKey('interests.id'), primary_key=True)
    active = db.Column(db.Boolean)
    interest = db.relationship('Interests', back_populates='owners')
    owner = db.relationship('Owners', back_populates='interests')


class Owners(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String)
    mobile = db.Column(db.String)
    interests = db.relationship('OwnersInterests', back_populates='owner')


class Interests(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String)
    owners = db.relationship('OwnersInterests', back_populates='interest')

但现在我想知道如何使用棉花糖模式准备 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

最佳答案

此架构为您提供了与您的规范非常相似的内容:

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

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

>>> from app.serialisation import OwnerSchema
>>> from app.models import Owner
>>> data = OwnerSchema().dump(Owner.query.get(1))
>>> from marshmallow import pprint
>>> pprint(data)
{"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}]}

让我缩进该输出,以便您可以看到发生了什么:

{
  "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
    }
  ]
}

如果需要,您可以对其进行调整以使用模型加排除范例。如果您确实想要 JSON 中的 "_embedded" 字段,您可能需要一个自定义字段,如 here 中所述。

您还可以使用自定义字段来展平您的兴趣,并将“active”字段置于与“id”“name”相同的级别,但我认为这会产生误导。

关于python - Flask Marshmallow 使用额外字段序列化多对多关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58391835/

相关文章:

python - 用 Python 中另一个 JSON 文件中的相应值替换 JSON 值

Python - 如何捕捉破损的管道

python - https 连接超时导致的 AWS Lambda 函数持续时间峰值

python - 使用 rebuild_index 的 Django Haystack 和 Elasticsearch 错误

serialization - Java 的 transient 在 Serde 中的等价物是什么?

php - 在数据库中存储数组

python - 如何让我的 flask wtforms SelectField 看起来像一个下拉菜单?

python - 使用 SQLAlchemy 和 Flask jsonify 返回 JSON 格式的连接表

python - 找不到 jinja2 模板和内部服务器错误

java - 如何发现 Java 反序列化问题?