I have something like this:
{
"id": 1,
"username": "plasmy",
"userdetails": [
{
"detail": "A Name",
"detail_name": "Full Name",
"id": 1,
"user_id": 1
},
{
"detail": "an@email.com",
"detail_name": "Email",
"id": 2,
"user_id": 1
},
{
"detail": "An Address",
"detail_name": "Address",
"id": 3,
"user_id": 1
},
{
"detail": "999-999-9999",
"detail_name": "Phone Number",
"id": 4,
"user_id": 1
}
]
}
This comes as a result from using Flask_Restless and SQLAlchemy. There is a table for users and a table for userdetails, which are put in the userdetails part of that JSON. What I want to do is, find a way in which the data can look like this:
{
"id": 1,
"username": "plasmy",
"userdetails": {
"Full Name": "A Name",
"Email": "an@email.com",
"Address": "An Address",
"Phone Number": "A Phone Number"
}
}
See how I removed the ids and I used the field "detail_name" as the key and "detail" as value. I tried using preprocessors but they didn't work or maybe I'm using them wrong. I put the preprocessor in the "child" table.
This is what I tried doing (but didn't work):
def detail_sort(results):
return {'user_details': results['userdetails']}
manager.create_api(User, methods=['GET', 'POST'])
manager.create_api(UserDetails, methods=['GET', 'POST'],
preprocessors={
'GET_COLLECTION': [detail_sort]
})
I tried GET_COLLECTION, GET_SINGLE and GET_MANY. Any help on this will be greatly appreciated.
UPDATE: Here is the new code I tried based on the answer
from flask import Blueprint
from medinv import manager
from medinv.User.models import User, UserDetails
blueprint = Blueprint('blueprint', __name__)
@blueprint.route('/')
@blueprint.route('/home')
def home():
return "Welcome."
def detail_sort(results):
print(results)
results['userdetails'] = {item['detail_name']: item['detail'] for item in results['userdetails']}
return results['userdetails']
manager.create_api(User, methods=['GET', 'POST'])
manager.create_api(UserDetails, methods=['GET', 'POST'],
postprocessors={
'GET_COLLECTION': [detail_sort]
})