How to group by? Django Rest Framework - json

I am developing an API Rest based on Django, I have two models:
Album
Track
I am trying to get the right format on this JSON (this is what I am getting now):
[
{
"album": "album-123kj23mmmasd",
"track": {
"id": 6,
"uuid": "2c553219-9833-43e4-9fd1-44f536",
"name": "song name 1",
},
"duration": 2
},
{
"album": "album-123kj23mmmasd",
"track": {
"id": 7,
"uuid": "9e5ef1da-9833-43e4-9fd1-415547a",
"name": "song name 5",
},
"duration": 4
},
This is what I would like to reach, I would like to group by 'albums':
[
{
"album": "album-123kj23mmmasd",
"tracks": [{
"id": 6,
"uuid": "2c553219-9833-43e4-9fd1-44f536",
"name": "song name 1",
"duration": 2
},
{
"id": 7,
"uuid": "9e5ef1da-9833-43e4-9fd1-415547a",
"name": "song name 5",
"duration": 4
},
]
},
]
EDIT 1: I am using Foreign Key instead ManyToMany
class Track(models.Model:
name, creation_date, etc...
class Album(models.Model):
track = models.Foreignkey(Track, on_delete=models.CASCADE)
Thanks in advance

SOLUTION:
Due the model complexity, I decided to user BaseSerializer, which allows to create custom response.

Related

Insert data type JSON in lighthouse php

I´m working in back graphql API with Laravel and Lighthouse.
I have a table with a column named "config" that stores json data.
I´m trying to create a new register to that table.
I have a mutation:
createOrderTemplate(name: String!, config: JSON!): OrderTemplate #create
The schema is:
type OrderTemplate {
id: ID!
name: String!
config: JSON!
}
I´ve tried the mutation in graphql-playground
mutation{
createOrderTemplate(
name:"SomeName",
config:
[{
"w_name": "Name1",
"w_code": "001",
"place": "Place1",
"job": "job1",
"data": [
{
"name": "name1",
"quantity": 2
},
{
"name": "name2",
"quantity": 2
},
{
"name": "name3",
"quantity": 1
},
{
"name": "name4",
"quantity": 2
}
]
},
{
"w_name": "Name2",
"w_code": "002",
"place": "Place2",
"job": "job2",
"data": [
{
"name": "name1",
"quantity": 2
},
{
"name": "name2",
"quantity": 2
},
{
"name": "name3"
"quantity": 1
},
{
"name": "name4",
"quantity": 2
}
]
}]
){
id
name
config
}
When I typed this I get an error, all is colored red and it does not execute anything.
What am I doing wrong?
Firstly, try to run that query in Insomnia, so you could see the exception that is thrown.
Moreover, I don't think that config gets a valid JSON value. Try first with a simple JSON like {key: 'value'}

T-SQL to retrieve part of data such as array using FOR JSON PATH

I am trying to retrieve the data from our SQL server in a specific way, basically I have a column and it has a delimiter ',' and need to convert like an array using FOR JSON PATH
I have tried using FOR XML PATH and FOR JSON PATH, but I don't figure out how to overcome this query.
Besides that, I have other ways to resolve, mapping using Entity Framework + LINQ, I needed to fix or understand if it is possible in SQL SERVER.
it is my simple data without FOR JSON:
and this is what I am doing:
select * from #templateData FOR JSON PATH
-- result
[
{
"id": 1,
"name": "Full Stack Engineer",
"description": ".net developer with 20 year of experience,Scrum master,Hold bachelor degree "
},
{
"id": 2,
"name": "Web Developer",
"description": "web dev"
},
{
"id": 3,
"name": "Full Stack Engineer",
"description": "tested"
}
]
an this is what I am expecting (see the column description)
[
{
"id": 1,
"name": "Full Stack Engineer",
"description": [
{".net developer with 20 year of experience"},
{"Scrum master"},
{"Hold a bachelor degree"},
],
},
{
"id": 2,
"name": "Web Developer",
"description": "web dev"
},
{
"id": 3,
"name": "Full Stack Engineer",
"description": "tested"
}
]
I have tried using STRING_SPLIT along with FOR JSON PATH using CROSS_APPLY however, without success.
Sorry I posted an incorrect comment before and removed it. I think you want something like this.
[EDIT]: Now it uses the framework splitter.
declare #json nvarchar(max)=N'[
{
"id": 1,
"name": "Full Stack Engineer",
"description": ".net developer with 20 year of experience,Scrum master,Hold bachelor degree "
},
{
"id": 2,
"name": "Web Developer",
"description": "web dev"
},
{
"id": 3,
"name": "Full Stack Engineer",
"description": "tested"
}
]'
;with j_cte(id, [name], [description]) as (
select * from openjson(#json) with (id int,
[name] nvarchar(200),
[description] nvarchar(4000)))
select id, [name],
(select [value] from string_split(j.[description], ',') for json path) [description]
from j_cte j for json path;
Which produces output:
[
{
"id": 1,
"name": "Full Stack Engineer",
"description": [
{
"Item": ".net developer with 20 year of experience"
},
{
"Item": "Scrum master"
},
{
"Item": "Hold bachelor degree "
}
]
},
{
"id": 2,
"name": "Web Developer",
"description": [
{
"Item": "web dev"
}
]
},
{
"id": 3,
"name": "Full Stack Engineer",
"description": [
{
"Item": "tested"
}
]
}
]

How to update the items on hand quantity with QuickBooks Online Plus

I am using QuickBooks Online Plus, which means i can edit the item. I would like to use the API to change the on hand # for an item. I've created an item "test1" through QuickBooks Online Plus. When i read the item from API i got the following in the attached json file. things looks great as follow:
{
"QueryResponse": {
"Item": [
{
"Name": "test1",
"Active": true,
"FullyQualifiedName": "test1",
"Taxable": false,
"UnitPrice": 3,
"Type": "Inventory",
"IncomeAccountRef": {
"value": "60",
"name": "Sales of Product Income"
},
"PurchaseCost": 1,
"ExpenseAccountRef": {
"value": "61",
"name": "Cost of Goods Sold"
},
"AssetAccountRef": {
"value": "62",
"name": "Inventory Asset"
},
"TrackQtyOnHand": true,
"QtyOnHand": 6,
"InvStartDate": "2015-12-02",
"domain": "QBO",
"sparse": false,
"Id": "19",
"SyncToken": "1",
"MetaData": {
"CreateTime": "2015-12-01T14:38:23-08:00",
"LastUpdatedTime": "2015-12-01T14:38:42-08:00"
}
}
],
"startPosition": 1,
"maxResults": 1
},
"time": "2015-12-02T09:59:29.936-08:00"
}
But when i tried to update that item using the json object below:
{
"Name": "test1",
"Active": true,
"Taxable": false,
"UnitPrice": 3,
"Type": "Inventory",
"IncomeAccountRef": {
"value": "60",
"name": "Sales of Product Income"
},
"PurchaseCost": 1,
"ExpenseAccountRef": {
"value": "61",
"name": "Cost of Goods Sold"
},
"AssetAccountRef": {
"value": "62",
"name": "Inventory Asset"
},
"TrackQtyOnHand": true,
"QtyOnHand": 16,
"InvStartDate": "2015-12-02",
"domain": "QBO",
"sparse": false,
"Id": "19",
"SyncToken": "2"
}
, i got an error like this:
{"Fault":{"Error":[{"Message":"Stale Object Error","Detail":"Stale Object Error : You and seven.li#hotschedules.com were working on this at the same time. seven.li#hotschedules.com finished before you did, so your work was not saved.","code":"5010","element":""}],"type":"ValidationFault"},"time":"2015-12-02T10:42:52.466-08:00"}
I would like to update the on hand quantity. Does anyone know what's wrong and how to do it? Thanks.
The problem is with the "SyncToken". I believe when you try to update the new item, you should not increment the "SyncToken", you should keep it the same. QBO will update the "SyncToken" for you.

Rearranging JSON output in Laravel

There are a few very similar questions, but not this exact thing. Let's start with my model:
Contest (hasMany Event, belongsToMany Player)
Player (hasMany Event, belongsToMany Contest, belongsToMany Event)
Event (belongsTo Contest, belongsToMany Players->withPivot('score)) (actually called ContestEvent since Event is a Laravel class)
I'm writing an API to do other stuff with the data. Right now I get this output from a given Contest:
{
"id": "1",
"owner_id": "1",
"name": "Some Contest",
"start_date": "2013-08-09",
"end_date": "2013-08-31",
"is_public": "1",
"is_finished": "0",
"players": [
{
"id": "1",
"first_name": "Bob",
"last_name": "Smith",
"initial_name": "Bob S",
"pivot": {
"contest_id": "1",
"user_id": "1"
}
}
],
"events": [
{
"id": "1",
"name": "Stage 1",
"date": "2013-08-01",
"players": [
{
"id": "1",
"first_name": "Bob",
"last_name": "Smith",
"initial_name": "Bob S",
"pivot": {
"contest_event_id": "1",
"user_id": "1",
"score": "5"
}
}
]
}
]
}
The pivot part is junk data, except for the score part under events. I can hide the whole pivot part with $hidden, but I want to access the score value one step up, outside of the pivot array.
I've messed around with $append and getFooAttribute(), but no success so far -- I can't quite figure out how to get Eloquent to do what I want. Any suggestions?
Rather than rearranging my model, I discovered Fractal, which made creating custom JSON output exactly the way you want it really easy.

Add Facebook json feed to a MySQL db

I guess this is a big ask. Using PHP I grab this Facebook Graph API json feed json feed link
{
"data": [
{
"id": "10369058551_10150645263758552",
"from": {
"name": "Land Rover",
"category": "Cars",
"id": "10369058551"
},
"message": "This week's Land Rover photo of the week is by Rodrigo Beja. Don't forget to submit your best photos each week to get featured.",
"link": "http://www.facebook.com/photo.php?fbid=10150645263678552&set=a.443106273551.221975.10369058551&type=1",
"icon": "http://static.ak.fbcdn.net/rsrc.php/v1/yz/r/StEh3RhPvjk.gif",
"actions": [
{
"name": "Comment",
"link": "http://www.facebook.com/10369058551/posts/10150645263758552"
},
{
"name": "Like",
"link": "http://www.facebook.com/10369058551/posts/10150645263758552"
}
],
"privacy": {
"description": "United Kingdom",
"value": "CUSTOM"
},
"type": "photo",
"object_id": "10150645263678552",
"created_time": "2012-02-03T17:19:03+0000",
"updated_time": "2012-02-03T22:32:28+0000",
"likes": {
"data": [
{
"name": "Mandy Elder",
"id": "100000250758731"
}
],
"count": 85
},
"comments": {
"data": [
{
"id": "10369058551_10150645263758552_6835532",
"from": {
"name": "John Sharp",
"id": "652940638"
},
"message": "This photo was used as part of the g4 challenge publicity photo pack around 2005-6 \nI remember because at the time I used it as a profile pic on msn \n\nAwesome photo - sums it up perfectly - I love it!!",
"created_time": "2012-02-03T21:39:48+0000"
},
{
"id": "10369058551_10150645263758552_6835852",
"from": {
"name": "Kathryn Piddington",
"id": "777370532"
},
"message": "Mud is good for the soul :)",
"created_time": "2012-02-03T22:32:28+0000"
}
],
"count": 14
}
},
{
"id": "10369058551_355476307803889",
"from": {
"name": "Land Rover",
"category": "Cars",
"id": "10369058551"
},
"message": "Click below to watch the new Range Rover Sport advert and catch up on the latest Land Rover and Range Rover news in this week\u2019s round-up. ",
"picture": "http://external.ak.fbcdn.net/safe_image.php?d=AQAx7xz602rfhyIn&w=90&h=90&url=http\u00253A\u00252F\u00252Fblog.landrover.com\u00252Fwp-content\u00252Fuploads\u00252F12my_rrs_044_LowRes.jpg",
"link": "http://blog.landrover.com/vehicles/the-land-rover-and-range-rover-weekly-19-3578.html#axzz1lKthI4F1",
"name": "The Land Rover and Range Rover Weekly 19 | Land Rover Blog",
"caption": "blog.landrover.com",
"description": "In this week\u2019s round-up of all things Land Rover and Range Rover, the new Range Rover Sport advert, Which? figures reveal the running costs of the Range Rover Evoque in comparison with competitors and a history of Land Rover narrated by Ranulph Fiennes.",
"icon": "http://static.ak.fbcdn.net/rsrc.php/v1/yD/r/aS8ecmYRys0.gif",
"actions": [
{
"name": "Comment",
"link": "http://www.facebook.com/10369058551/posts/355476307803889"
},
{
"name": "Like",
"link": "http://www.facebook.com/10369058551/posts/355476307803889"
}
],
"privacy": {
"description": "United Kingdom",
"value": "CUSTOM"
},
"type": "link",
"created_time": "2012-02-03T16:44:42+0000",
"updated_time": "2012-02-03T16:44:42+0000",
"likes": {
"data": [
{
"name": "Steve Nesbitt",
"id": "533982936"
}
],
"count": 10
},
"comments": {
"count": 0
}
},
{
"id": "10369058551_10150642499593552",
I'd like to the top level items to a mysql table, then each sub level to anaother table keeping a key / link between each table and then any sub level of a sublevel and linking this too. Is this possible?
I have got as far as this:-
$page = file_get_contents($url);
$json_output = json_decode($page, true);
I can't figure out how to loot hrough each row and add teh data to a Mysql table.
Thanks for your help in advance
Jonathan
Try to loop it as array then make sql query. Each array you put a unique key (for top level item). So, you can use your top level key to sub level foreign key..