每个建筑物都有单元,每个单元都与一个帐户相关联。一个单位可以有很多账户。每个单元只能有一个状态为“活动”的帐户。
API 返回所有单元的列表,每个单元中嵌套的是与该单元关联的所有帐户的列表。
如何返回相同的单位列表,但只返回与每个单位关联的活动帐户?
#model.py
class Unit(db.Model):
__tablename__ = 'units'
...
building_id = db.Column(db.Integer, db.ForeignKey('buildings.id'))
building = db.relationship("Building", back_populates="units")
accounts = db.relationship("Account", back_populates="unit")
class Account(db.Model):
__tablename__ = 'accounts'
id = db.Column(db.Integer, primary_key=True)
status = db.Column(sqlalchemy_utils.ChoiceType(STATUS_CHOICES))
...
#building.py
@api.route('/units')
class BuildingUnits(Resource):
@api.marshal_with(schemas.unit_fields, envelope='data')
def get(self):
""" Get list of all units
"""
return rbac.current_identity.building.units
#schemas.py
unit_fields = api.model('unit_fields', {
'id': fields.String,
...etc
...etc
'accounts': fields.List(fields.Nested(account_fields)),
})
account_fields = api.model('account_fields', {
'id': fields.String,
...etc
...etc
'status': fields.String(attribute=lambda x: getattr(x.status, 'value', 'Inactive')),
})