1

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')

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

Comments

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.