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')),
})
After asking someone (who Im not sure wants me to publicize who it is)
He responded as follows:
This is actually a good example why I tend to prefer to not use extensions to handle the API payloads. Sooner or later you find something that you need isn’t directly supported and you end up having to create compromise solutions.
What I would do in your case, is define a @property in your model that is maybe called active_account. This would be implemented as a database query that returns that one account that you want singled out. Then you can add “active_account” to your schema, so that Flask-RESTful renders it as a related item.
Hope this helps.
I think it was a great answer and it solved my problem.
I then followed up with:
Im not quite sure what you're referring to when you said: "why I tend to prefer to not use extensions to handle the API payloads."
Which extension are you referring to. What exactly would you do to implement what I have without using "extensions"
and he responded:
You are using Flask-RESTful, that is the extension I was referring to. I really have nothing against Flask-RESTful, works well, but I prefer to write my APIs in straight Flask.
And thats all folks, maybe later Ill post how I implemented what he said.