我可以手动对 SQLAlchemyAutoSchema 进行排序吗?

Can I sort my SQLAlchemyAutoSchema manually?

我刚刚开始使用 python 中的 marshmallow-sqlalchemy 包来处理我的烧瓶应用程序。一切正常,api 吐出我的数据库的内容,但似乎按字母顺序对字段进行排序,而不是我使用 SQLAlchemy.Model class 创建它们的顺序。现在我想知道是否有办法禁止或至少以某种方式手动对字段进行排序?

这就是我创建数据库的方式table:

class Product(db.Model):
    p_id = db.Column(db.Integer, primary_key=True)
    p_name = db.Column(db.String(100), nullable=False)
    p_type = db.Column(db.String, nullable=False)
    p_size = db.Column(db.Integer, nullable=False)
    p_color = db.Column(db.String, nullable=False)

    def __repr__(self):
        return f"Product(name={self.p_name}, type={self.p_type}, size={self.p_size}, color={self.p_color})"

这是我的架构:

class ProductSchema(SQLAlchemyAutoSchema):
    class Meta:
        ordered = True     #I have read about this property on another post, but doesn't do anything here
        model = Product

我的函数以 json 格式返回内容:

    def get(self, id):
        if id:
            product = Product.query.filter_by(p_id=id).first()
            if product:
                product_schema = ProductSchema()
                output = product_schema.dump(product)
            else:
                abort(Response('product not found', 400))
        else:
            products = Product.query.all()
            products_schema = ProductSchema(many=True)
            output = products_schema.dump(products)
        return jsonify(output), 200

Aa 和我得到的输出(按字母顺序排序):

[
  {
    "p_color": "test color1", 
    "p_id": 1, 
    "p_name": "test name1", 
    "p_size": 8, 
    "p_type": "test type1"
  }, 
  {
    "p_color": "test color2", 
    "p_id": 2, 
    "p_name": "test name2", 
    "p_size": 8, 
    "p_type": "test type2"
  }, 
  {
    "p_color": "test color3", 
    "p_id": 3, 
    "p_name": "test name3", 
    "p_size": 8, 
    "p_type": "test type3"
  }, 
  {
    "p_color": "test color4", 
    "p_id": 4, 
    "p_name": "test name4", 
    "p_size": 8, 
    "p_type": "test type4"
  }
]

如上所述,我的应用程序功能齐全。但我至少想知道发生了什么。所以感谢任何帮助!

默认情况下,Flask 在转储 json 输出时对键进行排序。这样做是为了确定顺序,从而允许计算哈希等。

the docs

您可以使用 JSON_SORT_KEYS 参数禁用此功能。

如果您想调试 marshallow 部分,只需在视图函数中打印转储 (output)。

除非您有充分的理由强制执行输出顺序,否则最好还是放手。

注意:在 flask-smorest 中,我不介意有效负载在响应中按字母顺序排列,但我喜欢在发布 OpenAPI 规范文件时按顺序排列,所以我不修改 JSON_SORT_KEYS 并且在服务规范文件的资源,I don't use jsonify but raw json.dumps.