I m trying to send model data as json using below code
Views.py
def autocomplete(request):
model = NewCarModel.objects.only('car_model_new')
print('model is',model)
# users_list = list(model)
posts_serialized = serializers.serialize('json', model)
print('post is',posts_serialized)
return JsonResponse(posts_serialized,safe=False)
models.py
class NewCarModel(models.Model):
car_model_new = models.CharField(max_length=100, unique=True)
def __str__(self):
return self.car_model_new
output:
"[{\"model\": \"core.newcarmodel\", \"pk\": 1, \"fields\": {\"car_model_new\": \"swift\"}}, {\"model\": \"core.newcarmodel\", \"pk\": 2, \"fields\": {\"car_model_new\": \"wagonr\"}}, {\"model\": \"core.newcarmodel\", \"pk\": 3, \"fields\": {\"car_model_new\": \"baleno\"}}, {\"model\": \"core.newcarmodel\", \"pk\": 4, \"fields\": {\"car_model_new\": \"breeza\"}}, {\"model\": \"core.newcarmodel\", \"pk\": 5, \"fields\": {\"car_model_new\": \"spresso\"}}]"
why there is bunch of backslash in my JSON output and how i can remove them and Mozilla Firefox default JSON filter is also not working, neither i am able to extract data from it using java script(as i am able to extract data from some public API so there is no problem with extract code)
edit:
how I m trying to extract data after parsing JSON into variable myArr
const carModelsArr = myArr.data.map((d) => d.fields.car_model_new
edit 2: so solution of not able to extact is instead of
var myArr = JSON.parse(this.responseText);
used this:
var myArr = JSON.parse(JSON.parse(this.responseText));
and extract code is able to work
but still, doesn't solve backslash problem and I would like to avoid using DRF if possible