我在使用序列化模型对象的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
此模式提供了与您的规范非常相似的内容:
然后,您可以像这样序列化您的数据(请注意,我的模型与您的模型的名称不完全相同):
^{pr2}$让我缩进输出,这样您就可以看到发生了什么:
如果需要的话,您可以调整它以使用model plus exclude范式。如果您真的希望在JSON中使用
"_embedded"
字段,那么您可能需要一个自定义字段,如here所述。在您还可以使用自定义字段来简化您的兴趣,并将}放在同一级别,但我认为这会误导您。在
"active"
字段与"id"
和{相关问题 更多 >
编程相关推荐