我想在棉花糖3中将is_active
列的嵌套字段过滤为True
考虑以下方案
我有3张桌子
users (id, name)
organizations (id, name)
organization_user(id, organization_id, user_id, is_active)
现在,我正在尝试打印所有组织及其活动成员。 (有一些活跃和不活跃的成员)
我有以下架构
class OrganizationSchema(ma.ModelSchema):
members_list = fields.Nested(OrgnizationUserSchema, many=True, exclude=('checklist', ))
class OrgnizationUserSchema(ma.ModelSchema):
user_list = fields.Nested(UserSchema)
现在在我的操作中,下面是代码
organization_schema = OrganizationSchema(many=True)
#Query for list of organization
organization_list = Organization.query.all()
organization_schema.dump(organization_list)
以下为输出
[
{
'id': 1,
'name': 'abc',
'members_list': [
{'id':1, 'organization_id': 1, 'user_id':1, 'is_active':True},
{'id':1, 'organization_id': 1, 'user_id':2, 'is_active':False}
]
}
]
我希望与具有'is_active':True
的成员进行如下输出
[
{
'id': 1,
'name': 'abc',
'members_list': [
{'id':1, 'organization_id': 1, 'user_id':1, 'is_active':True}
]
}
]
棉花糖提供装饰器@post_dump
。这里的问题是查询带来了所有数据,然后我们用装饰器@post_dump
对其进行过滤。
但是流程应该是这样,在查询时应该有某种方法可以过滤数据,而不是在查询后进行过滤。
答案 0 :(得分:2)
我走了另一条路。我有布料,设计和余数。对于每种面料,我需要获取所有设计,并且对于每种设计,都需要获取指定城市的余数。
class ClothSchema(Schema):
id = fields.Integer(dump_only=True)
name = fields.String(validate=not_blank)
type = fields.Nested(ClothTypeSchema)
designs = fields.Nested(DesignSchema, many=True)
class DesignSchema(Schema):
id = fields.Integer(dump_only=True)
name = fields.String(validate=not_blank)
remainders = fields.Nested(RemainderSchema, many=True)
class RemainderSchema(Schema):
id = fields.Integer(dump_only=True)
value = fields.String()
city = fields.String()
我在控制器中获得了我需要的数据,以便在旅途中不要求它们。
db.session.query(Cloth)
.join(Cloth.designs)
.join(Design.remainders)
.filter(Remainder.city == city)
.options(contains_eager("designs").contains_eager("remainders"))
结果,我得到了剩下的所有衣服和所有设计。如果未显示剩余的设计,则不会显示。
{
"attributes": {
"designs": {
"data": [
{
"attributes": {
"name": "Amely 10 ",
"remainders": {
"data": [
{
"attributes": {
"city": "CityEnum.MOSCOW",
"value": "333"
},
"id": 9318,
"type": "remainder"
}
]
}
},
"id": 365,
"type": "design"
}
],
"links": {
"self": "/designs"
}
},
"name": "Amely",
"rapport": null,
"type": {}
},
"id": 22,
"type": "cloth"
}