简体   繁体   中英

How can I JSON serialize a queryset on Django?

I'd like to return on my ajax response a queryset, this is the error I get when I try to serialize a queryset.

TypeError: 'Font: FontName' is not JSON serializable

I am using JSON response like so :

...
return JsonResponse({
    'foo': Font.objects.filter(id=1).first(),
})

I also tried, same error :

response = json.dumps({
    'foo' : tmp_fonts,
})

return HttpResponse(response, content_type='application/json')

third try :

AttributeError: 'str' object has no attribute '_meta'

# tmp_fonts = [<Font:CaviarDream>, <Font:Arial>, <Font:Calibri>, etc...]

return JsonResponse({
    'foo': serializers.serialize('json', tmp_fonts),
})

I'd like to be able to get it back on response and display every fields in the query on my template. Is this even possible ?


Model :

class UserInfo(models.Model):
    organisation = models.CharField(max_length=255)
    font = models.ManyToManyField(Font)

class Font(models.Model):
    name = models.CharField(max_length=255)

So the short version is:

from django.http import JsonResponse
from django.views import generic
from .models import Font


class FontListAjaxView(generic.View):
    def get(self, *args, **kwargs):
        return JsonResponse(data=list(Font.objects.values()), safe=False)
        # or the "safe" version, where data needs to be dictionary:
        # return JsonResponse(data={'data': list(Font.objects.values()))

Solution : That is what worked for querysets in list.

# tmp_fonts = [<Font:CaviarDream>, <Font:Arial>, <Font:Calibri>, etc...]

response = JsonResponse({
    'foo' : serializers.serialize('json', tmp_fonts),
})

return HttpResponse(response, content_type='application/json')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM