Abz Rockers
Abz Rockers

Reputation: 338

How to return JSON Response correctly in joining multiple table in Django

Currently I am using Django 1.10.
For example we have the models below:

class ModelOne(models.Model):
  description = models.CharField(max_length = 50)
class ModelTwo(models.Model):
  description = models.CharField(max_length = 50)
  m1 = models.ForeignKey( ModelOne)
class ModelThree(models.Model):
  description = models.CharField(max_length = 50)
  m2 = models.ForeignKey(ModelTwo)

Everytime a request is made then a JSON response is return using the code below:

from app.models import *
from django.http import HttpRequest,JsonResponse

def ViewThatReceiveRequest(request):
  qs = list(ModelThree.objects.filter(description__icontains='beauty').select_related('m2__m1')
  data = []
  for key in qs:
    temp_obj = {}
    # if necessary I will convert the values before equating
    temp_obj['desc3'] = key.description
    temp_obj['desc2'] = key.m2.description
    temp_obj['desc1'] = key.m2.m1.description
    data.append(temp_obj)
  return JsonResponse( {'message' : 'success', 'qs' : data }, safe = False)

Note:
- I am using Django as my back-end and ReactJs for my front-end so I only need JSON Response

My question,
- Do I need to do these for every views that receive request?
- Do we have other way to solve these simpler?

Upvotes: 0

Views: 1643

Answers (1)

iamkhush
iamkhush

Reputation: 2592

Since you only need description field from all 3 models, you can also use values method or maybe values_list of the queryset and get data.

So this new query would be ModelThree.objects.filter(description__icontains='beauty').select_related('m2__m1).values_list('description','m2__description','m2__m1__description')

Next if you want to run some changes to your data, you can run a map method in case you want to make similar changes to all the data.

Next you can make the appropriate json and send to to client side.

Upvotes: 1

Related Questions