0

I am trying to create an endpoint but I keep getting an error: "Object of type model is not JSON serializable".

I tried passing it through list() and json.dumps() but it int work. I tried printing the query and it was like

[<Lead: Test>, <Lead: user2>, <Lead: user3>, <Lead: user4>]

Here is the code I wrote:

def leads(request):
    full = []
    lead_list = list(Lead.objects.all())
    print(lead_list)
    for i in lead_list:
        full.append(json.dumps(i))
    print(full)
    return JsonResponse(list(full), safe=False)

Here are a few question I looked at and tried:

Output Django queryset as JSON

I tried serializing it with serializer but the response was like this:

"[{\"model\": \"leads.lead\", \"pk\": 1, \"fields\": {\"first_name\": \"Test\", \"last_name\": \"User\", \"age\": 25, \"city\": \"kolkata\", \"country\": \"India\", \"email\": \"ankr@gmail.com\", \"agent\": 1, \"status\": \"Potential\"}}, {\"model\": \"leads.lead\", \"pk\": 2, \"fields\": {\"first_name\": \"user2\", \"last_name\": \"test2\", \"age\": 44, \"city\": \"Mumbai\", \"country\": \"India\", \"email\": \"test2@gmail.com\", \"agent\": null, \"status\": \"prospect\"}}, {\"model\": \"leads.lead\", \"pk\": 4, \"fields\": {\"first_name\": \"user3\", \"last_name\": \"test3\", \"age\": 19, \"city\": \"Paris\", \"country\": \"France\", \"email\": \"test3@gmail.com\", \"agent\": null, \"status\": \"Prospect\"}}, {\"model\": \"leads.lead\", \"pk\": 8, \"fields\": {\"first_name\": \"user4\", \"last_name\": \"test4\", \"age\": 33, \"city\": \"London\", \"country\": \"UK\", \"email\": \"test4@gmail.com\", \"agent\": null, \"status\": \"Converted\"}}]"
indianLeo
  • 153
  • 1
  • 11

1 Answers1

0

you need to serialize your queryset then use JsonResponse.

class LeadSerializer(serializers.ModelSerializer):
    class Meta:
        model = Lead
        fields = '__all__'

def leads(request):
    qs= Lead.objects.all()
    serializer = LeadSerializer(qs,many=True)
    return JsonResponse(serializer.data, safe=False)

PS: since i don't know the columns in your Lead Model i am using ModelSerializer for serializing, However you can write your own custom serializer using serializers.Serializer also by mentioning your each column like

class LeadSerializer(serializers.Serializer):
    name = serializer.CharField(max_length=10)
    column_1 = serializer.IntegerField()
wheezay
  • 101
  • 7
  • I tired it but is shows` [OrderedDict(), OrderedDict(), OrderedDict(), OrderedDict()]` – indianLeo Jan 24 '21 at 08:34
  • I have edited the answer, I had forgot to add class meta in serializer and mapping it with the model. I have tried it myself and it is returning me desired values – wheezay Jan 24 '21 at 09:33