有序 = True 不受尊重。蟒蛇+棉花糖+烧瓶

时间:2021-03-25 20:08:22

标签: python marshmallow

又是我,现在有一个棉花糖问题,我有以下结构:

路由.py

@models.response(ParentSchema())
def get(args, model_id):

    return {"response": {"a": [{"data": "a"}], "b": [{"data": "a"}], "c": [{"data": "a"}], "d": [{"data": "a"}]}}

然后这是我的模式文件 架构.py

class SubChildSchema(Schema):
    data = fields.Str(description="Model's name")


class ChildSchema(Schema):

    class Meta:
        ordered = True

    a = fields.Nested(SubChildSchema, many=True)
    b = fields.Nested(SubChildSchema, many=True)
    c = fields.Nested(SubChildSchema, many=True)
    d = fields.Nested(SubChildSchema, many=True)


class ParentSchema(Schema):
    response = fields.Nested(ChildSchema)

假设在响应中我应该得到一个排序的响应,如:

{
    "response": {
        "a": [
            {
                "data": "a"
            }
        ],
        "b": [
            {
                "data": "a"
            }
        ],
        "c": [
            {
                "data": "a"
            }
        ],
        "d": [
            {
                "data": "a"
            }
        ]
    }
}

但不是我收到的

{
    "response": {
        "b": [
            {
                "data": "a"
            }
        ],
        "c": [
            {
                "data": "a"
            }
        ],
        "d": [
            {
                "data": "a"
            }
        ],
        "a": [
            {
                "data": "a"
            }
        ]
    }
}

看起来 ChildSchema 类上的属性 orders=True 不起作用 我一直在一些帖子中寻找这个问题,看起来当您混合嵌套字段和有序属性时会出现问题。

这是我的堆栈

flask-marshmallow==0.14.0
marshmallow==2.21.0
marshmallow-sqlalchemy==0.23.1

1 个答案:

答案 0 :(得分:3)

我发现您可以尝试两种不同的策略:

在应用定义之后将此配置行添加到您的代码中:

app = Flask (__ name__)
app.config ['JSON_SORT_KEYS'] = False

抑制烧瓶字典键排序并强制遵守定义的顺序。

您也可以尝试在 ParentSchema 类中添加用于排序键的相同元数据,因为 ChildSchema 包含在 ParentSchema 中;我们也需要指定 ParentSchema 以尊重键顺序。

类似的东西

class ParentSchema(Schema):
    class Meta:
        ordered = True

    response = fields.Nested(ChildSchema)

我希望你觉得这有用,问候

相关问题