I'm developing an API with flask_restplus and flask_sqlalchemy, and I have a special case where certain applications should access only certain columns from the API.
I have a model:
class MyModel(db.Model):
__tablename_ = 'my_table'
id = db.Column(db.Integer, primary_key=True)
first_column = db.Column(db.Unicode)
second_column = db.Column(db.Unicode)
I also have specified a flask_resplus' model to be returned from the API:
my_model = api.model('MyModel',
{'first_column': fields.String(),
'second_column': fields.String()})
Where api is a flask_restplus' Api instance and db a flask_sqlachmey's instance.
Sometimes I want to select only some of the columns, and for the other column to be null in the api.model that is returned as a JSON repsonse.
After searching on the Internet, I found two methods which neither of them work in my case:
load_only() from sqlalchemy.orm, which returns the columns as a list. As a result, I can't return those results, since my model expects a dictionary with same keys as described in my_model. The other method, with_entities() returns an instance of MyModel, which is what I need, but it loads all the columns at the time I pass that instance to the my_model, since it does only a lazy selection, i.e. it selects the specified columns, but if the other columns are required, it does a query again to get the values of other columns, thus loading, in my case, all the columns, which is not what I want.
How can I do a SQL SELECT where only some of the columns are returned and the result is an instance of the db.Model?