Django + rest-framework: serialize arbitrary query - json

I have three classes representing different sections in my models: SectionA, SectionB, SectionC.
Each of these sections have associated a set of items (class Item in my model).
I would like to get a json similar to this:
{
"sectionA": [
{
"id": 1,
"picture": "car_pic1",
"category": "cat1"
},
{
"id": 3,
"picture": "car_pic1",
"category": "cat2"
},
{
"id": 5,
"picture": "car_pic1",
"category": "cat3"
}
],
"sectionB": [
{
"id": 2,
"picture": "car_pic1",
"category": "cat8"
},
{
"id": 4,
"picture": "car_pic1",
"category": "cat9"
},
{
"id": 7,
"picture": "car_pic1",
"category": "cat10"
},
],
"sectionC": [
{
"id": 9,
"picture": "car_pic1",
"category": "cat9"
},
{
"id": 10,
"picture": "car_pic1",
"category": "cat9"
},
{
"id": 11,
"picture": "car_pic1",
"category": "cat10"
},
]
}
This json displays any three items associated to each section.
I would like to know how can I implement this using rest-framework. Basically I need to perform a query retrieving the three items for each section (since this json is not associated to a model object) and serialize all this into the json. I'm not sure where or how to perform these queries and I didn't have any success so far.

Finally I did it slightly different. My view just creates a dictionary with each section and its associated items:
class SectionList(APIView):
"""
List three objects for each section.
"""
def generate_data(self):
#query to get the items of each section
list_items = []
list_items.append({"section" : "sectionA", "items" : secA_items})
list_items.append({"section" : "sectionB", "items" : secB_items})
list_items.append({"section" : "sectionC", "items" : secC_items})
return list_items;
def get(self, request, format=None):
section_list = self.generate_data()
serializer = SectionSerializer(section_list)
return Response(serializer.data)
And this is the serializer I used:
class SectionSerializer(serializers.Serializer):
section = serializers.CharField(max_length=200)
items = ItemSerializer(many=True)

Related

How to dynamically add object inside json array?

I'm trying to dynamically add an object inside every object which is present in my json array. But I'm unable to do so. My object is getting appended at the end of json which is not what I want.
jsonArray:any=[
{
"id": 1000,
"body": "some comment",
"postId": 1
},
{
"id": 2,
"body": "some comment",
"postId": 1
},
{
"id": 3,
"body": "some comment",
"postId": 1
}
]
selectFLag:any={"selected":"true"}
temArray:any;
learnJSONPArse()
{
for (var i = 0; this.jsonArray.length > i; i++)
{
Alert(this.jsonArray.length)
}
}
this.jsonArray.push(this.selectFLag)
-----expected output is
[
{
"id": 1000,
"body": "some comment",
"postId": 1,
"selected":"true"
},
{
"id": 2,
"body": "some comment",
"postId": 1,
"selected":"true"
},
{
"id": 3,
"body": "some comment",
"postId": 1,
"selected":"true"
}
]
You're question is a little unclear, but it sounds like you want to map each item in your array to a new item. The new item is the same as the old one, but assigned an additional property.
If so, something like this could work for you:
const objToAppend = { selected: true };
jsonArray.map(item => Object.assign(item, objToAppend));
Refs:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

Render Nested json objects in React Native

In my render() method i need to parse nested json objects. See the portion of render and json structure below.
I access Last Name with {params.name_last}.
How will i access items under team, like team.name_first
render() {
let { params } = this.props.navigation.state
<Text>{params.name_last}</Text>
}
[
{
"id": 1,
"name_first": "Name first 1",
"name_middle": "",
"name_last": "Name last 1",
"name_suffix": "",
"phone": "888-8888",
"fax": "888-8888",
"updated_at": "2015-11-02T21:42:42.000Z",
"team": [
{
"id": 16,
"name_first": "aaa",
"name_middle": "",
"name_last": "bbb",
"name_suffix": ""
},
{
"id": 28,
"name_first": "aaa",
"name_middle": "",
"name_last": "bbb",
"name_suffix": ""
},
{
"id": 29,
"name_first": "aaa ",
"name_middle": "",
"name_last": "bbb",
"name_suffix": ""
}
]
}
]
Since team is an array, you need to either access a specific entry in the array, or iterate over the entire thing.
To reach a specific property in the nested array entry (assuming you want the object at index i):
params.team[i].name_first
To create an array of first names:
params.team.map(x => x.name_first)

Remove pivote attribute from JSON response in Laravel 5.2

I'm using many to many relationships using pivot table. But the problem is when I'm returning json response, the json also contains the pivot attribute as shown below:
{
"id": 2,
"job_title": "et",
"job_description": "Iusto provident.",
"job_industry": "Braun, Jast and Quigley",
"job_location": "Christiansenland",
"job_experience": 7,
"employment_type": "full",
"recruiter_id": 9,
"status": 1,
"posted_date": "2016-02-02 07:55:28",
"skills": [
{
"id": 1,
"value": "molestiae",
"pivot": {
"job_id": 2,
"skill_id": 1
}
}
]
}
What I want is something like this:
{
"id": 2,
"job_title": "et",
"job_description": "Iusto provident.",
"job_industry": "Braun, Jast and Quigley",
"job_location": "Christiansenland",
"job_experience": 7,
"employment_type": "full",
"recruiter_id": 9,
"status": 1,
"posted_date": "2016-02-02 07:55:28",
"skills": [
{
"id": 1,
"value": "molestiae",
}
]
}
I have tried various solutions from the stackoverflow questions, but none of them seem to work. I'm new to Laravel. If you guys need more info on the model,I can post it. Please help.
Go to your Skill model and set:
protected $visible = ['id', 'value'];

Serialize the response from backend to store ember store

My response from backend is not in form which ember store. I am not able to serialize the response.
response.json
[{
"pk": 127,
"url": "http://example.com/api/galleries/127/",
"gallery_name": "Faces",
"thumbnail_url": "https://example.cloud.net/galleryThumbs/2656a05c-4ec7-3eea-8c5e-d8019454d443.jpg",
"time": "1 month ago",
"description": "Created by user",
"is_following": true,
"feedPhotos": [{
"pk": 624,
"url": "http://example.com/api/photos/624/",
"profilePic": "https://example.cloud.net/userDPs/50906ce2-394d-39c8-9261-8cf78e3611c2.jpg",
"userName": "Nabeela",
"userKarma": 915,
"caption": "Old woman spinning her 'chhos-khor' ...a rotation of which is equivalent to the recitation of a mantra.",
"numComments": 0,
"owner": "http://example.com/api/users/44/",
"time": "1 month ago",
"photo_url": "https://example.cloud.net/photos/9cbd6423-3bc5-36e0-b8b4-d725efb3249a.jpg",
"comments_url": "http://example.com/api/photos/624/comments/",
"numFives": 4,
"fivers_url": "http://example.com/api/photogalleries/1362/fivers/",
"fivers_pk": 1362,
"fullphoto_url": "http://example.com/api/photogalleries/1362/photo/",
"fullphoto_pk": 1362,
"is_fived": true,
"hiFiveKarma": 1,
"owner_pk": 44,
"userFirstName": "Nabeela",
"is_bookmarked": false
}, {
"pk": 574,
"url": "http://example.com/api/photos/574/",
"profilePic": "https://example.cloud.net/userDPs/b6f69e4e-980d-3cc3-8b3e-3eb1a7f21350.jpg",
"userName": "Rohini",
"userKarma": 194,
"caption": "Life # Myanmar!",
"numComments": 0,
"owner": "http://example.com/api/users/45/",
"time": "2 months ago",
"photo_url": "https://example.cloud.net/photos/eeae72d5-d6af-391e-a218-b442c0c7e34e.jpg",
"comments_url": "http://example.com/api/photos/574/comments/",
"numFives": 2,
"fivers_url": "http://example.com/api/photogalleries/1303/fivers/",
"fivers_pk": 1303,
"fullphoto_url": "http://example.com/api/photogalleries/1303/photo/",
"fullphoto_pk": 1303,
"is_fived": false,
"hiFiveKarma": 0,
"owner_pk": 45,
"userFirstName": "Rohini",
"is_bookmarked": false
}
]
}, {
"pk": 65,
"url": "http://example.com/api/galleries/65/",
"gallery_name": "Royal",
"thumbnail_url": "https://example.cloud.net/galleryThumbs/d8a900af-1f1d-3977-8cc8-b8bb36e32be5.jpg",
"time": "2 months ago",
"description": "This is a gallery about Royal",
"is_following": false,
"feedPhotos": [{
"pk": 347,
"url": "http://example.com/api/photos/347/",
"profilePic": "https://example.cloud.net/userDPs/50906ce2-394d-39c8-9261-8cf78e3611c2.jpg",
"userName": "Nabeela",
"userKarma": 915,
"caption": "I cannot forget the name of this palace - Moti Mahal (translation: Pearl Palace). Indescribably beautiful, ainnit! at Mehrangarh fort, Jodhp",
"numComments": 0,
"owner": "http://example.com/api/users/44/",
"time": "2 months ago",
"photo_url": "https://example.cloud.net/photos/958ed406-708e-3f01-a2f4-9467cd709fdd.jpg",
"comments_url": "http://example.com/api/photos/347/comments/",
"numFives": 4,
"fivers_url": "http://example.com/api/photogalleries/759/fivers/",
"fivers_pk": 759,
"fullphoto_url": "http://example.com/api/photogalleries/759/photo/",
"fullphoto_pk": 759,
"is_fived": false,
"hiFiveKarma": 0,
"owner_pk": 44,
"userFirstName": "Nabeela",
"is_bookmarked": false
}, {
"pk": 593,
"url": "http://example.com/api/photos/593/",
"profilePic": "https://example.cloud.net/userDPs/95ac6974-f7df-338c-ab84-99fa1df7514c.jpg",
"userName": "Vikanshu",
"userKarma": 932,
"caption": "Marvelous architecture!! in Florence, Italy",
"numComments": 0,
"owner": "http://example.com/api/users/48/",
"time": "1 month ago",
"photo_url": "https://example.cloud.net/photos/7a86eb37-6c68-3d6c-b6cf-2e3b74d330dd.jpg",
"comments_url": "http://example.com/api/photos/593/comments/",
"numFives": 4,
"fivers_url": "http://example.com/api/photogalleries/1363/fivers/",
"fivers_pk": 1363,
"fullphoto_url": "http://example.com/api/photogalleries/1363/photo/",
"fullphoto_pk": 1363,
"is_fived": false,
"hiFiveKarma": 0,
"owner_pk": 48,
"userFirstName": "Vikanshu",
"is_bookmarked": false
}]
}]
How do I serialize this using JSONPISerailizer or any other serializer in ember-cli so that it gets stored in ember store
Reference jsonapi.org
++++Top Level:
Root:
A JSON object must be root of every JSON API request response.
A document must contain at least one top-level members:
1. data: documents "primary data"
2. errors: an array of error objects (id,status,code,title....)
3. meta: a meta object that contains non-standard meta-information (copyright,author...)
member data and errors must not co-exist together.
"data"{}
+++++Resource Objects
1. A resource object MUST contain atleast following top-level member
*id
*type
```
//structure-1
//for galleries
{
"data": {
"type": "galleries",
"id": "1"
}
}
//for photos
{
"data": {
"type": "photos",
"id": "1"
}
}
```
In addition, a resource object may contain any of these top-level members
*attributes
*relationship
*links
*meta
//added attributes first
```
//structure-2
//for galleries
{
"data": {
"type": "galleries",
"id": "1",
"attributes": {
"galleryName": "Faces"
"thumbnailUrl:"https://example.cloud.net/galleryThumbs/2656a05c-4ec7.jpg",
"description": "Created by user",
}
}
}
//for photos
{
"data": {
"type": "photos",
"id": "1",
"attributes":{
userName: "Nabeela",
userKarma: 915
}
}
}
```
//Adding relationship
Relationship object must contain atleast one of the following
*links (containing atleast one of "self" or "related" resource link
*data
*meta
//link in relationship (minimum one required from link,data,meta).
//
```
//structure-3
//for galleries
{
"data":[{ //Array(square bracket as adding relationship one more item to data
"type": "galleries",
"id": "1",
"attributes": {
"galleryName": "Faces"
"thumbnailUrl:"https://example.cloud.net/galleryThumbs/2656a05c-4ec7.jpg",
"description": "Created by user",
},
"relationships":{
"links":{
"self": "https://example.cloud.net/photos/9cbd6423.jpg //"photo_url" in your payload
},
}]
}
}
```
//data in relationship
```
//structure-4
//for galleries
{
"data": [{
"type": "galleries",
"id": "1",
"attributes": {
"galleryName": "Faces"
"thumbnailUrl:"https://example.cloud.net/galleryThumbs/2656a05c-4ec7.jpg",
"description": "Created by user",
},
"relationships":{ //This has all your photo stuff
"links":{
"self": "https://example.cloud.net/photos/9cbd6423.jpg //"photo_url" in your payload
},
"data": { //picked it up from structure-1
"type": "photos",
"id": "77"
}
}]
}
}
```
//Adding related resource "included"
```
//for galleries
{
"data": [{
"type": "galleries",
"id": "1",
"attributes": {
"galleryName": "Faces"
"thumbnailUrl:"https://example.cloud.net/galleryThumbs/2656a05c-4ec7.jpg",
"description": "Created by user",
},
"relationships":{ //This has all your photo stuff
"links":{
"self": "https://example.cloud.net/photos/9cbd6423.jpg //"photo_url" in your payload
},
"data": { //picked it up from structure-1
"type": "photos",
"id": "77"
}
}],
"included":[{
"type": "photos",
"id": "77",
"attributes":{
userName: "Nabeela",
userKarma: 915
},
{
"type": "photos",
"id": "78",
"attributes":{
userName: "Nabeela",
userKarma: 915
}
}]
}
}
```
For collections. I am not confident but try this
Now for collection of galleries.
//for galleries
{
"data": [{
"type": "galleries",
"id": "1",
"attributes": {
"galleryName": "Faces"
"thumbnailUrl:"https://example.cloud.net/galleryThumbs/2656a05c-4ec7.jpg",
"description": "Created by user",
},
"relationships":{ //This has all your photo stuff
"links":{
"self": "https://example.cloud.net/photos/9cbd6423.jpg //"photo_url" in your payload
},
"data": { //picked it up from structure-1
"type": "photos",
"id": "77"
}
},{
"type": "galleries",
"id": "2",
"attributes": {
"galleryName": "Faces"
"thumbnailUrl:"https://example.cloud.net/galleryThumbs/2656a05c-4ec7.jpg",
"description": "Created by user",
},
"relationships":{ //This has all your photo stuff
"links":{
"self": "https://example.cloud.net/photos/9cbd6423.jpg //"photo_url" in your payload
},
"data": { //picked it up from structure-1
"type": "photos",
"id": "79"
}
}],
"included":[{
"type": "photos",
"id": "77",
"attributes":{
userName: "Nabeela",
userKarma: 915
},{
"type": "photos",
"id": "78",
"attributes":{
userName: "Nabeela",
userKarma: 915
},{
"type": "photos",
"id": "79",
"attributes":{
userName: "Nabeela",
userKarma: 915
}
}]
}
}
============Implementation part =================================
JSONSerializer normalization process follows these steps
*normalizeResponse : entry method.
*normalizeCreateRecordResponse : a normalizeResponse for specific operation.
*normalizeSingleResponse|normalizeArrayResponse:
- for methods like createRecord. we expect a single record back.
- for methods like findAll we expect multiple records back.
+normalize =
normalizeArray iterates and calls normalize for each of it's records
normalizeSingle call its once.
+extractID | extractAttributes | extractRelationships
= normalize delegates to these method to turn record payload into jsonAPI format
Starting with normalizeResponse method. If you open and see normalizeResponse method
in json-serializer
link normalizeResponse: https://github.com/emberjs/data/blob/v2.2.1/packages/ember-
data/lib/serializers/json-serializer.js#L192
you with find a switch case switch(requestType). If requestType if
"findRecord" then "normalizeFindRecordResponse" is called
"queryRecord" then "normalizeQueryRecordResponse" is called
"findAll" then "normalizeFindAllResponse" is called
...so on and so forth.
if you notice the parameter passed to all the methods are same as that of normalize
(...arguments) :)
**Lets start for findAll
i.e normalizeResponse -> normalizeFindAllResponse -> normalizeArrayResponse
as normalizeFindAllResponse method has only one line that call
normalizeArrayResponse.
normalizeFindAllResponse
normalizeResponse -> normalizeFindAllResponse -> normalizeArrayResponse ->
_normalizeResponse{ extractMeta,normalize }
extractMeta [extract meta information like pagination and stuff ]
if single: normalize []
example of normalize method in emberjs docs
```
import DS from 'ember-data';
export default DS.JSONSerializer.extend({
normalize: function(typeClass, hash) {
var fields = Ember.get(typeClass, 'fields');
fields.forEach(function(field) {
var payloadField = Ember.String.underscore(field);
if (field === payloadField) { return; }
hash[field] = hash[payloadField];
delete hash[payloadField];
});
return this._super.apply(this, arguments);
}
});
```
"normalizeArrayResponse calls `return this._normalizeResponse
(store,primaryModelClass,payload,id,requestType,false).
so isSingle is false for _normalizeResponse method. so we will have to push all the
related records of included array
in our case the photos which is done by below snippet from "_normalizeRespose"
method.
_normalizeResponse
```
else{
documentHash.data = payload.map((item) => {
let { data, included } = this.normalize(primaryModelClass,item);
if(included){
documentHash.included.push(...included);
}
return data;
});
return documentHash;
}
```
Things are still unclear in the context of our JSON reponse from server
but atleast we know the flow now.
Lets try to apply it for findAll ( as per the flow above).
run "ember g serializer application" //assuming you are using ember-cli and you
intend to make this serializer generic for application.
As of now I have no information how and when normalizeResponse is called. :(
I just scanned through and guess on recieving data from server the store calls
normalizeResponseHelpers which in turn calls normalizeResponse.
In any case "normalizeResponse" is going to send payload and other necessar
information to normalizeFindAllResponse(...arguments) which in turn will call
normalizeArrayResponse(...arguments) which in turn will call "_normalizeRespone".
Here is where we need to take action
for extraMeta and normalize.
+extraMeta
I am not sure if there is any meta information in you json response.
in case there is you can refer to the example mentioned in docs
extractMeta
So I guess you can directly user the normalize method from example in your application ;).
please try and check. Since i am learning ember myself I cannot guarantee it will work but it should. the lonngggg explation is my thought while i was learning the problem/solution
//app/serializers/application.js
+normalize
```
import DS from 'ember-data';
export default DS.JSONSerializer.extend({
normalize: function(typeClass, hash) {
var fields = Ember.get(typeClass, 'fields');
fields.forEach(function(field) {
var payloadField = Ember.String.underscore(field);
if (field === payloadField) { return; }
hash[field] = hash[payloadField];
delete hash[payloadField];
});
return this._super.apply(this, arguments);
}
});
```
The primary key in the JSON from server is pk. You will have to mention that too
http://emberjs.com/api/data/classes/DS.JSONSerializer.html#property_primaryKey
app/serializers/application.js
import DS from 'ember-data';
export default DS.JSONSerializer.extend({
primaryKey: 'pk'
});

Customise ActiveRecord JSON Response without a Serializer

I'm rendering some JSON using sinatra/contrib. I want to customise my JSON response not to include "teacher_id" in the associated record. How do I do this?
get '/teachers' do
json Teacher.includes(:courses).all.as_json(include: :courses)
end
Will render:
{
"id": 1,
"name": "Dave",
"age": 27,
"specialism": "Ruby",
"courses": [
{
"id": 1,
"title": "WDI",
"teacher_id": 1
}
]
}
I would like to remove, teacher_id:
{
"id": 1,
"name": "Dave",
"age": 27,
"specialism": "Ruby",
"courses": [
{
"id": 1,
"title": "WDI"
}
]
}
I can use the except: syntax to remove id, name, age and specialism. How can I remove the associated property?
Thanks in advance.
You can use the :except option for associations like this:
Teacher.includes(:courses).all
.as_json(include: { courses: { except: :teacher_id } })