Every building has units and every unit is associated with an account. There can be many accounts associated with a unit. There can only be one account per unit with a status of "active".
The API returns a list of all the units, and nested within each unit is a list of all the accounts associated with that unit.
How can I return the same list of units but only the active account associated with each?
#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')),
})