jhon1946
jhon1946

Reputation: 183

how to pass objects with django and ajax?

I have an application in Django 2.0 in which I use a template with an ajax function from which I want to receive the result of a filter but it generates the following error:

TypeError: <QuerySet [<Curso: Curso object (1)>, <Curso: Curso object (2)>, <Curso: Curso object (3)>]> is not JSON serializable

Views.py

def activaAjax(request):
    curso = Curso.objects.filter(pk = request.GET['id'])
    cursos = Curso.objects.all()
    try:
        curso.update(estado=Case(When(estado=True, then=Value(False)),When(estado=False, then=Value(True))))
        mensaje = "Proceso de ACTIVACIÓN/INACTIVACIÓN correcto!!!"
        data = {'mensaje': mensaje, 'cursos':cursos}
        return HttpResponse(json.dumps(data), content_type="application/json")
    except:
        return HttpResponse(json.dumps({"mensaje":"Error"}), content_type='application/json', status = 500)
    return HttpResponse(json.dumps({"mensaje":"Error"}), content_type='application/json')

Upvotes: 1

Views: 573

Answers (1)

Parth Modi
Parth Modi

Reputation: 291

Queryset can not be directly dump in json by json.dumps() either you should write queryset.values_list('field1',flat=True) or if you want more than 1 field from object you should write queryset.values_list('field1','field2',..) convet it to list with list(queryset.values_list('field1','field2',..)) and pass it in your data as

data = { 'corsos' : list(queryset.values_list('field1','field2',..)) }

2) Or you can also do

from django.core import serializers

serialized_qs = serializers.serialize('json', queryset)
data = {"queryset" : serialized_qs}
return JsonResponse(data)

Upvotes: 1

Related Questions