MY VIew
def cargar_categorias(request):
data = serializers.serialize("json", MyModel.objects.all())
return HttpResponse(data, mimetype='aplication/json')
回应json
[{"pk": 8, "model": "MyModel.MyModel", "fields": {"celular": "234342342", "logo": "recetas/aurelio.jpg", "tipo": 1, ....
但字段“tipo”是外键,我需要恢复此字段的值而不是id(1)
我的Jquery代码
$.ajax({
type: "GET",
contentType: "application/json; charset-utf-8",
dateType: "json",
url: "/cargar_categorias",
success: function(response){
var i=(response.length-1)-6;
for( i;i<=(response.length-1);i++){
$('#locations').append("<li data-celular='"
+ response[i].fields.celular +"' data-tipo='"
+ response[i].fields.tipo +"'><img href=#"
+ response[i].fields.logo +" src='/media/"
+ response[i].fields.logo +"'/></li>");
}
}
});
我认为可以使用select_related()但不能使用,或者响应[i] .fields.tipo.nombre或.... 我现在不用,请帮助我,这很疯狂,对不起我的英语
答案 0 :(得分:0)
解决此问题的一种可能方法是根据查询集的返回值构建自己的字典对象。你可以这样做:
queryset = MyModel.objects.all()
list = [] #create list
for row in queryset: #populate list
list.append({'celular':row.celular, 'logo': row.logo, 'tipo': row.tipo.id})
list_json = json.dumps(list) #dump list as JSON
return HttpResponse(list_json, 'application/javascript')