我收到json无法序列化的错误。
views.py
def get_post(request):
if request.is_ajax():
if request.method=="GET":
craves = CraveData.objects.filter(person=request.user)
print craves
response = json.dumps({"craves":craves})
return HttpResponse(response,mimetype="application/json")
crave.html
function next(){
alert("you in")
$.ajax({
url: "/crave/get_post/",
type: "GET",
data: "",
success: function(response){
alert('success');
alert(response.craves)
//$('.ajaxProgress').html(response.HTML_USER);
$('.ajaxProgress').html(response.craves);
},
error:function(){
alert('some error');
}
});
}
我正在TypeError: [<CraveData: Gaurav>, <CraveData: Rahul>] is not JSON serializable
但是当我试图获得
时craves = len(CraveData.objects.filter(person=request.user))
我正在获得价值。请帮助我在模板中获取对象。
答案 0 :(得分:2)
使用正确的serializer:
from django.core import serializers
def get_post(request):
if request.is_ajax():
if request.method=="GET":
craves = CraveData.objects.filter(person=request.user)
response = serializers.serialize('json', craves)
return HttpResponse(response, mimetype="application/json")