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