0

I am working on a project and i am stuck on registration API.Or I should override drf_multiple_models?.I am getting this response by the views that I have provided and I don't want response like this:

{
"message": "success",
"code": 200,
"country": [
    {
        "country_name": "nepal",
        "country_code": "977"
    }
],
"postal code": [
    {
        "post_code": 105
    }
],
"suburb": [
    {
        "suburb_name": "damak"
    }
],
"state": [
    {
        "state_name": "india1"
    }
]
}

but i need response like this:

{
"message": "success",
"code": 200,
"country": [
        {
        "country_name": "nepal",
        "country_code": "977"
        }
        "postal code":
            {
                "post_code": 105
            }
        "suburb":
            {
                "suburb_name": "damak"
            }
        "state":
            {
                "state_name": "india1"
            }
        }]

here is my views:

class InformationList(APIView):
    def get(self, request):
        country=self.request.query_params.get('country')
        post = self.request.query_params.get('post')
        city = self.request.query_params.get('city')
        state = self.request.query_params.get('state')

        query1 = Country.objects.filter(country_code=country).values('country_name', 'country_code')
        query2 = Post.objects.filter(post_code=post).values('post_code')
        query3 = Suburb.objects.filter(suburb_name=city).values('suburb_name')
        query4 = State.objects.filter(state_name=state).values('state_name')

        return Response({"message": "success", "code":status.HTTP_200_OK,"country": query1, "postal code": query2, "suburb": query3,
                     "state": query4})

need help. thanks in advance

0

2 Answers 2

1

Your queries are right, all you have to do is change the response,

 Response({"message": "success", "code":status.HTTP_200_OK,"country": query1[0], "postal code": query2[0], "suburb": query3[0],
                     "state": query4[0]})

The main reason you need to change your response is because queryset using filter creates lists of objects. If you don't want list around objects, use 'get()'

Sign up to request clarification or add additional context in comments.

Comments

0

maybe you should try to keep all the data under a single variable such as:

dict = {}
dict['countries'] = query1, query2, query3, query4
return Response(dict)

and call dict as response. this might work, as of now you are calling each response independent and they appear in the given order that your output is showing

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.