2

I have created a views function in django which returns the data of all influencers. Now I want to add the functionality that a user can make multiple lists and then add those influencers to any of the list created by them. The lists created by the users are displayed in the form of a drop down menu in front of the influencers name. How should I create the API so that the list created by the users are displayed in front of the influencers.
P.S: I want to create the API without using django rest framework.
This is what I have tried till now:

def index(request):
    influencers = Influencer.objects.all()

    influencer_data = serializers.serialize("json",influencers) 
    user_list = UserList.objects.all().filter(user_id = request.user.id)
    user_list = serializers.serialize("json",user_list)
    context = {
        'influencer_data':influencer_data,
        'user_list':user_list,

    }


    return HttpResponse(json.dumps(context),content_type='application/json')

I am getting the result as:

{"influencer_data": "[{\"model\": \"influencer_listings.influencer\", \"pk\": 8794, \"fields\": {\"full_name\": \"F A I Z S H A I K H \\ud83c\\udf08\", \"username\": \"mr_faizzz_07\", \"photo\": \"\", \"email_id\": \"\", \"external_url\": \"\ 
.............................
.............................
"user_list": "[{\"model\": \"user_listings.userlist\", \"pk\": 21, \"fields\": {\"user_id\": 5, \"list_name\": \"Campaign 1\"}}, {\"model\": \"user_listings.userlist\", \"pk\": 22, \"fields\": {\"user_id\": 5, \"list_name\": \"Delhi Campaign\"}}]"}

The return statement makes the JSON object returned a string.I want the data to be returned in the JSON format.

3
  • 1
    show us what have you tried ? Commented Jun 20, 2019 at 6:02
  • I haven't tried anything yet. Commented Jun 20, 2019 at 6:07
  • 1
    then try something and then ask if you get any errors Commented Jun 20, 2019 at 6:07

1 Answer 1

3
from itertools import chain
from django.http import HttpResponse
from django.core import serializers

def index(request):

    user_list = UserList.objects.all().filter(user_id=request.user.id)
    influencers = Influencer.objects.all()
    queryset = list(chain(user_list, influencers ))
    ser_query = serializers.serialize('json', queryset)
    return HttpResponse(ser_query)

Do it like this, modify the code to your needs

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

3 Comments

I want to send the information from both influencer_data as well as user_list, not just user list.It works fine with just one object but makes the JSON a string when two objects are passed.
modified a bit.
How to do if i'm using class based view?

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.