【发布时间】:2021-05-24 05:01:09
【问题描述】:
我刚刚开始在 python 中为我的烧瓶应用程序使用 marshmallow-sqlalchemy 包。一切正常,api 吐出我的数据库的内容,但似乎按字母顺序对字段进行排序,而不是我使用 SQLAlchemy.Model 类创建它们的顺序。现在我想知道是否有办法禁止这样做,或者至少以某种方式手动对字段进行排序?
这就是我创建数据库表的方式:
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"
}
]
如上所述,我的应用程序功能齐全。但我至少想知道发生了什么。因此,我们非常感谢您的帮助!
【问题讨论】:
标签: python flask flask-sqlalchemy marshmallow