JSON serializers not working in Django
Hay, serializers is not returning JSON object
make = Make.objects.filter(slug__exact=make)
models = Model.objects.filter(make=make).values('slug','name')
json_models = serializers.get_serializer("json")()
开发者_JAVA百科 json_models.serialize(models)
return HttpResponse(json_models.getvalue())
I'm getting an error
'dict' object has no attribute '_meta'
Any ideas?
As the other answer hints, its because .values(...)
returns a list and serializers
is meant for Querysets. However you can still do this without needing raw SimpleJSON quite simply:
queryset = Model.objects.filter(make__slug__exact=make)
return serializers.serialize("json", queryset, fields=('slug', 'name'))
We're basically telling the serializer to do the field-limiting instead of letting the Queryset doing it. I've used some shortcuts in there to cut the query down to one line too but that's up to you.
The serializer is meant to be used on QuerySet
instances. Use django.utils.simplejson.dumps()
if you have a normal Python structure.
精彩评论