问题背景
笔者需要在前端显示数据库中一条记录的详细信息,使用datatable按照表格的方式进行展现。如下图所示, 用户在输入一本书的ISBN号码以及UUID之后,点击“OK”按键,后台在执行对应操作之后, 前端会显示对应书籍的详细信息, 以表格的形式呈现。 比如图中的《JavaScript高级程序设计》书籍信息。
API格式定义
后端在接受到前端的请求之后,以JSON格式返回信息给前端,数据格式如下:
{
"status":value,
"msg": value,
"bindbook":value,
}
前端datatable的定义如下:
$("#sample_1").dataTable(
{
searching : false,
destroy : true,
"processing" : true,
"serverSide" : false,
"autoWidth" : false,
"bLengthChange" : false,
"ajax": {
"url": "#",
"dataSrc": "bindbook",
"type": "POST",
"data": function (d) {
d.isbn=document.getElementById('id_isbn').value;
d.uuid=document.getElementById('id_uid').value
},
dataFilter:function(data,json){
r = JSON.parse(data)
if (r.status == "OK"){
console.log("信息添加成功");
}else{
console.log(r.msg);
}
$("#id_querylibbookForm")[0].reset();
return data;
}
},
"columns": [
{ data: 'name' },
{ data: 'isbn' },
{ data: 'author' },
{ data: 'press' },
{ data: 'price' },
{ data: 'totalAmount' },
{ data: 'outAmount' },
{ data: 'totalOutAmount' },
{ data: 'totalBrokenAmount' }
],
});
});
我们在前端datatable中定义的dataSrc 指定为返回数据中的bindbook field。
Django 后台代码如下:
status = ''
msg = ''
r = []
if form.is_valid():
isbn = form.cleaned_data['isbn']
uid = form.cleaned_data['uuid']
status = "OK"
msg = "Bind book success !!"
book = libraryBookImport(isbn, uid)
serializer = BooklistSerializer(book)
resp = {
'status': status,
'msg': msg,
'bindbook': serializer.data,
}
return HttpResponse(json.dumps(resp), content_type="application/json")
问题: datatable无法正确显示后台返回的数据
问题分析
经过调试发现,如果后端返回的是多个数据项,前端就能正常显示。返回多个数据的代码如下:
serializer=BooklistSerializer(book.objects.all(), many=True)
那么看一下这两种情况下生成的json数据有什么不同
- 返回一条数据
{
"status": "",
"msg": "",
"bindbook": {
"name": "\u9c7c\u7f8a\u91ce\u53f2\u00b7\u7b2c3\u5377",
"isbn": 9787513905817,
"author": "\u9ad8\u6653\u677e",
"press": "\u6c11\u4e3b\u4e0e\u5efa\u8bbe\u51fa\u7248\u793e",
"price": 3979,
"totalAmount": 25,
"outAmount": 0,
"totalOutAmount": 1,
"totalBrokenAmount": 0,
"cover": "/media/lpic/default_cover.jpg"
}
}
- 返回多条数据
{
"status": "",
"msg": "",
"bindbook": [{
"name": "\u4f1a\u5458\u5361",
"isbn": 0,
"author": "\u53ee\u549a\u56fe\u4e66",
"press": "\u53ee\u549a\u56fe\u4e66",
"price": 1980,
"totalAmount": 0,
"outAmount": 0,
"totalOutAmount": 0,
"totalBrokenAmount": 0,
"cover": "/media/lpic/default_cover.jpg"
}, {
"name": "JavaScript\u9ad8\u7ea7\u7a0b\u5e8f\u8bbe\u8ba1",
"isbn": 9787115275790,
"author": "[\u7f8e]",
"press": "\u4eba\u6c11\u90ae\u7535\u51fa\u7248\u793e",
"price": 9900,
"totalAmount": 1,
"outAmount": 0,
"totalOutAmount": 5,
"totalBrokenAmount": 0,
"cover": "/media/lpic/default_cover.jpg"
}]
}
仔细观察了这两个数据, 在bindbook域,一条数据的时候缺一个中阔号[ ]
解决办法
将后台代码改为
r=[]
serializer = BooklistSerializer(book)
r.append(serializer.data)
前端datatable就能正常显示了。
结语
关于django-rest-framework的serializer的传送门其实也有体现两者的区别:
- 官网介绍单个object序列化
serializer = CommentSerializer(comment)
serializer.data
# {'email': '[email protected]', 'content': 'foo bar', 'created': '2016-01-27T15:17:10.375877'}
- 官网介绍多个object序列化
queryset = Book.objects.all()
serializer = BookSerializer(queryset, many=True)
serializer.data
# [
# {'id': 0, 'title': 'The electric kool-aid acid test', 'author': 'Tom Wolfe'},
# {'id': 1, 'title': 'If this is a man', 'author': 'Primo Levi'},
# {'id': 2, 'title': 'The wind-up bird chronicle', 'author': 'Haruki Murakami'}
# ]
这个小问题卡了好久,真是书到用时方恨少。