How to pass model fields to a JsonResponse object How to pass model fields to a JsonResponse object python python

How to pass model fields to a JsonResponse object


For future reference, .values() returns a ValuesQuerySet that behaves like a iterable full of dictionaries, so using the list() will make a new instance of a list with all the dictionaries in it. With that, you can create a new dict and serialize that.

response = JsonResponse(dict(genres=list(Genre.objects.values('name', 'color'))))

IIRC, it's not safe to have a JSON object that has a list as root and that's probably why Django is complaining. I couldn't find any reference about that now to provide a source, sorry.


To pass nondictionary values to the JsonResponse as you retrieved with Genres.object.values('name','color') you can simple set the safe argument to false and it will return JSON.

from django.http import JsonResponsedef django_json(request):    data = Genres.object.values('name','color')    return JsonResponse(data, safe=False)

That should return a list of JSON of the values you specified. Check out my article How to Return a Json Response with Django for more detailed info on how this works.

Alternatively, if you would like to return a queryset back as JSON you can use Djangos core serializer like this:

from django.core.serializers import serializefrom django.http import JsonResponsefrom .models import Genredef django_models_json(request):    qs = Genre.objects.all()    data = serialize("json", qs, fields=('name', 'color'))    return JsonResponse(data)

This will return the same as above.