In DRF, how to get dictionary format in JSON response rather than List of dcitionaries - django

How to get dictionary format in JSON response rather than List of dictionaries. Right now am getting response like list of dictionaries and I want to get response without list.
#Response I get for example
[
{
"id": 40,
"full_name": "Don Ser 1",
"email": "Donny#sfds.com",
"phone": 12345,
"address_line_1": "sdsdsdsd",
"address_line_2": "dsdsdsd",
},
{
"id": 41,
"full_name": "Don Ser 2",
"email": "Donny#sfds.com",
"phone": 121356456,
"address_line_1": "sdsdsdsd",
"address_line_2": "dsdsdsd",
}
]
#Response I Like to get is without List.
[
{
"id": 40,
"full_name": "Don Ser 1",
"email": "Donny#sfds.com",
"phone": 12345,
"address_line_1": "sdsdsdsd",
"address_line_2": "dsdsdsd",
},
{
"id": 41,
"full_name": "Don Ser 2",
"email": "Donny#sfds.com",
"phone": 121356456,
"address_line_1": "sdsdsdsd",
"address_line_2": "dsdsdsd",
}
}
How do I achieve this?
Additionally I like to know why it returned it in List rather than dictionary?

If you want to return a dict you must define a structure, e.g.
{'results': [
{
"id": 40,
"full_name": "Don Ser 1",
"email": "Donny#sfds.com",
"phone": 12345,
"address_line_1": "sdsdsdsd",
"address_line_2": "dsdsdsd",
},
{
"id": 41,
"full_name": "Don Ser 2",
"email": "Donny#sfds.com",
"phone": 121356456,
"address_line_1": "sdsdsdsd",
"address_line_2": "dsdsdsd",
}
]}
But just return a dict without a key is not possible.

If you are returning your response in DRF with serializer.data the simplest way to achieve that is:
return Response(serializer.data[0], status=status.HTTP_200_OK)
If you want to include the whole dictionary in another dictionary you'd have to give it a key so it would something like this:
return Response({"results":serializer.data[0]}, status=status.HTTP_200_OK)
Otherwise if you are using it on a simple item you can just specify it the way you want i.e. :
serializer = Serializer(data=request.data)
if serializer.is_valid():
device = serializer.save()
return Response({"pk": device.id}, status=status.HTTP_201_CREATED)

Related

How to get the last createdAt item with TypeORM

Hi friends I need help with this query that I want to make to return only the last 'Case' by 'User'.
On my PostMan request I have my service that returns all the cases that the user have made.
users.services.ts
async findCasesbyUserId(id: number) {
return await this.usersRepository.findOne(id, { relations: ['cases']})
}
users.controller.ts
#Get('/findCase/:id')
async findCasesByUserId(#Param('id', ParseIntPipe) id: number,) {
return this.usersService.findCasesbyUserId(id)
}
When I made my GET request to 'http://localhost:3000/users/findCase/3'. This is the result that I get.
The user with id=3 have the cases with the id=1, id=2, id=3
So I want only to return only the case with the id=3 because is the last created case. I need a way to get the last case by the field createdAt or another way could be great for me.
Im using NestJs with TypeORM for thew querys to my PostgreSQL DB.
{
"id": 3,
"createdAt": "1617983079621",
"updatedAt": "1617983079621",
"name": "John",
"lastname": "Doe",
"email": "jdoe#email.com",
"username": "JohnDoe",
"password": "**************",
"role": "Admin",
"isActive": true,
"document": "12345",
"address": "Test",
"phone": "12345",
"cases": [
{
"id": 1,
"createdAt": "1618504530817",
"updatedAt": "1618504530817",
"message": "Test Case 1",
},
{
"id": 2,
"createdAt": "1618504530817",
"updatedAt": "1618504530817",
"message": "Test Case 1",
}, {
"id": 3,
"createdAt": "1618546146772",
"updatedAt": "1618546146772",
"message": "Test Case 1",
},
]
}

How to pass json data as queryset object to django template?

I have this json data in views.py
[
{
"id": 6,
"first_name": "Star",
"last_initial": "W",
"phone": "+918893972142",
"email": "star#gmail.com",
"date_created": "2020-10-12T17:17:17.629123Z",
"orders": []
},
{
"id": 4,
"first_name": "Sam",
"last_initial": "0",
"phone": "+918766897214",
"email": "sam#gmail.com",
"date_created": "2020-10-12T17:13:33.435065Z",
"orders": []
},
{
"id": 3,
"first_name": "Gaara",
"last_initial": "W",
"phone": "+918668972789",
"email": "gaara#gmail.com",
"date_created": "2020-10-12T17:08:44.906809Z",
"orders": [
{
"order_id": "9",
"customer_id": "3",
"customer_name": "Gaara W",
"product_id": "3",
"product_name": "Jet",
"date_created": "2020-10-12T17:18:18.823289Z",
"status": "Delivered"
}
]
}
]
I want to pass this data as a context object to the template from views using render function. so I can display this data using {% for %} loop in my template.
Pass the data into the template.
return render(request, "app/template.html", {
"data": data
})
Then you can use for loops to render the data you need.

what's the use if I am querying all the database before pagination in Django?

as per below code I am doing the query for database then I am paginating the query result. so My question what's the use if we already hit the database for all result before pagination. Is this like Django pagination working or I am pretending something wrong?
I am getting the response as expected but had question querying the database before pagination.
Code:
class GetAllUserStoryListViewTest(APIView,LimitOffsetPagination):
permission_classes = (IsAuthenticated,)
def get_object(self,user_id):
user = User.objects.filter(id = user_id).first()
posts = Post.objects.filter(user = user)
return posts
def get(self,request,user_id):
posts = self.get_object(user_id).order_by('-post_time_stamp')
#setting the limit of this user post pagination
LimitOffsetPagination.default_limit = settings.PAGE_SIZE
posts = self.paginate_queryset(posts, request)
serializer_context = {
'request': request,
}
serializer = PostListSerializer(posts,many=True,context=serializer_context)
# return Response(serializer.data)
return self.get_paginated_response(serializer.data)
output:
{
"count": 7,
"next": "http://127.0.0.1:8000/api/list_all_story_test/27/?limit=2&offset=5",
"previous": "http://127.0.0.1:8000/api/list_all_story_test/27/?limit=2&offset=1",
"results": [
{
"id": 15,
"file": "http://127.0.0.1:8000/media/user_27/post/IMG_20190331_144024.jpg",
"post_info": "#cool",
"post_time_stamp": "2020-05-10T10:21:10Z",
"total_comment": 2,
"liked_by": [
"vipin"
],
"user": {
"id": 27,
"username": "vipin",
"email": "vipinks#xyz.edu",
"status": true,
"profile": {
"id": 24,
"full_name": "Vipin",
"mobile": 6732,
"background_picture": "http://127.0.0.1:8000/media/user_27/profile/pexels-photo-531880_0qSgRNx.jpeg",
"profile_picture": "http://127.0.0.1:8000/media/user_27/profile/IMG_20190331_144024.jpg",
"BioDescription": "xyz",
"date_of_birth": "1996-06-01",
"gender": "M",
"account_type": "Private",
"user": 27
},
"last_login": null,
"is_superuser": false,
"is_staff": false,
"is_active": true,
"date_joined": "2020-04-28T11:09:27.691478Z"
},
"comment_usr": [
"xyz",
26,
"Cool Pic"
],
"like_by_you": true
},
{
"id": 13,
"file": "http://127.0.0.1:8000/media/user_30/post/IMG_20190402_102248.jpg",
"post_info": "#Awesome",
"post_time_stamp": "2020-05-10T10:20:22Z",
"total_comment": 8,
"user": {
"id": 30,
"username": "xyz",
"email": "xyz#gmail.com",
"status": false,
"profile": {
"id": 27,
"full_name": "XYZ",
"mobile": 123,
"background_picture": null,
"profile_picture": "http://127.0.0.1:8000/media/user_30/profile/demo.jpg",
"BioDescription": null,
"date_of_birth": null,
"gender": "F",
"account_type": "Private",
"user": 30
},
"last_login": null,
"is_superuser": false,
"is_staff": false,
"is_active": true,
"date_joined": "2020-04-28T11:13:58.030941Z"
},
"like_by_you": true
}
]
}
The pagination hit the database with Count() method, to paginating the result.
And, in every page hit the database by slicing that is more efficient than
using a queryset with all() method and, hit the database with Iteration, which load all the results.
filter() or all() methods don't hit the database. See this to check when a QuerySet is evaluated.

I have the JSON. How can I fetch student_id, first_name, and second_name?

This is JSON I parsed from a URL. Now I want student_id, first_name, and second_name from this JSON. How can i get that?
[{
"timestamp": "2017-06-29 05:37:23",
"student_id": "6",
"first_name": "SACHIN",
"second_name": "SINGH",
"sex": "male",
"student_course": "TECH-NON-TECH",
"email_id": "sachinsinghchahar9058841073#gmail.com",
"password": "kbmss#10002",
"phone": "8879505608",
"login_id": "kbmss",
"status": "2",
"roll_no": "",
"payment": "cash",
"amount_description": "cash",
"amount": "8500",
"refrence_id": "",
"child_id": "0",
"plan": "advance",
"valid_upto": "2017-12-14"
}]
switch response.result{
case .success(let data) :
let json = JSON(data)
For more explanation you can go to this link.
How to get values of an array of dictionary from alamofire response using swift3

How to nest a serializer?

So I'm trying to create an /api/info url that return various data on my application. It pulls data from various models and puts it together in one response. I got the following:
class SessionInfo(generics.GenericAPIView):
def get(self, request, format=None):
token = Token.objects.get(user=self.request.user)
userprofile = UserProfile.objects.get(user=self.request.user)
is_admin = self.request.user.is_staff
is_primary_owner = userprofile.primary_owner
managers = userprofile.reports_to.all()
man = ["test manager 1", "test manager 2"]
pages = Page.objects.filter(published=True, show_in_menu=True)
pages_output = JSONRenderer().render(PageSerializer(pages).data)
content = {
'user': {
"username": str(self.request.user.username),
"first_name": str(self.request.user.first_name),
"last_name": str(self.request.user.last_name),
"is_admin": is_admin,
"is_primary_owner": is_primary_owner,
"api_token": token.key,
"timezone": 'blalala',
"managers": man,
},
'license': {
"plan" : "gold",
"expiry_date" : "lol",
},
'feature_flags': {
'billing_test': False,
},
'pages': { pages_output },
}
return Response(content)
However it doesn't properly serialize and render pages, making it an escaped string instead:
{
"feature_flags": {
"billing_test": false
},
"user": {
"username": "test#user.com",
"first_name": "Test",
"last_name": "User",
"is_admin": true,
"managers": [
"test manager 1",
"test manager 2"
],
"api_token": "08d1a5827da9a90e7746949ffd2e69e87c51b272",
"timezone": "blalala",
"is_primary_owner": false
},
"license": {
"expiry_date": "lol",
"plan": "gold"
},
"pages": [
"[{\"id\": 1, \"title\": \"Trololol\"}, {\"id\": 2, \"title\": \"NEW pages\"}]"
]
}
if I use directuly use pages_output = PageSerializer(pages) I get:
<webapp_api_v1.serializers.PageSerializer object at 0x10a0d8f90> is not JSON serializable
How can I make a serializer properly nest within my constructed response? Thanks!
Solved it with pages_output = PageSerializer(pages).data and changing 'pages': pages_output,