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\"}}]"