我提供了下面的javascript。请注意写着"老师"的那个。这个老师基本上是外键。然而,当我尝试console.log行时,它并没有向我显示特定的数组值作为对象或作为对象返回的数据,而是返回一个字符串,因为它在django模型上使用def __str__
。因此,我无法得到特定的值,即teacher.first_name
或本例中的data.first_name
,结果为undefined
注:我使用django-datatable -view来提供ajax url。
$(document).ready( function () {
$('.table').DataTable({
"columnDefs": [
{
name: 'date_created',
orderable: true,
searchable: true,
targets: [0],
},
{
name: 'name',
orderable: true,
searchable: true,
targets: [1],
},
{
name: 'email',
orderable: true,
searchable: true,
targets: [2],
},
{
name: 'phone',
orderable: true,
searchable: true,
targets: [3],
},
{
name: 'course',
orderable: true,
searchable: true,
targets: [4],
},
{
name: 'remarks',
orderable: true,
searchable: true,
targets: [5],
},
{
name: 'teacher',
orderable: true,
searchable: true,
targets: [6],
render: function(data, type, row){
return data.first_name + "<br>(" + data + ")"
}
},
{
name: 'is_enrolled',
orderable: true,
searchable: true,
targets: [7],
render: function(data, type, row){
if (data === "True"){
return "<i class='fa fa-check text-success text'></i>"
}
else{
return "<i class='fa fa-times text-danger text'></i>"
}
}
},
{
name: 'status',
orderable: true,
searchable: true,
targets: [8],
},
{
name: 'get_lead.owner',
orderable: true,
searchable: true,
targets: [9],
},
],
order: [],
"processing": true,
"language": {
processing: '<i class="fa fa-spinner fa-spin fa-3x fa-fw"></i><span class="sr-only">Loading...</span> '},
"serverSide": true,
"ajax": "{% url 'referrals-json' %}",
scrollY: 500,
dom : 'flrBtip',
searchHighlight: true,
buttons : [
{ extend: 'excel', text: 'Export', className: 'btn-primary' }
],
"lengthMenu": [ [10,50,100,-1], [10,50,100,"All"] ]
});
} );
[EDIT]添加更多信息以清除内容。对行和数据执行console.log,即
render: function(data, type, row){
console.log(row, data)
}
得到以下结果。观察第6个数组元素,它是字符串而不是对象。
Array(10) [ "2021-10-16 06:25:36+00:00", "Vibula", "testmail@gmail.com", "96779*****", "EMAESTER", "He/She is IT by profession || Looking for online teaching Job", "anotheremail@gmail.com", "False", "Not Dialed", "" ]
0: "2021-10-16 06:25:36+00:00"
1: "Vibula"
2: "testmail@gmail.com"
3: "96779*****"
4: "EMAESTER"
5: "He/She is IT by profession || Looking for online teaching Job"
6: "anotheremail@gmail.com"
7: "False"
8: "Not Dialed"
9: ""
length: 10
<prototype>: Array []
anotheremail@gmail.com
我完全错过了库提供的方法,即'render_column',做完全相同的事情渲染选项在数据表jquery部分。我是这样做的:
def render_column(self, row, column):
# We want to render teacher as a custom column
if column == 'teacher':
print row.teacher.first_name, row.teacher.email
# escape HTML for security reasons
return '{0}<br>({1})'.format(row.teacher.first_name, row.teacher.email)
else:
return super(ReferralsJSON, self).render_column(row, column)