Is there an example showing how to use DataTables in conjunction with Django models?
Is there an example showing how to use DataTables in conjunction with Django models?
daneboy55
Posts: 10Questions: 1Answers: 0
I initialize datatable with this:
$(document).ready(function() {
$('#mytable').DataTable( {
"ajax":{
"processing": true,
"dataSrc": "",
"url": "{% url 'Sensor_ajax_url' %}"
}
} );
} );
my view looks like this:
def Sensor_asJson(request):
object_list = Sensor.objects.all()
json = serializers.serialize('json', object_list)
return HttpResponse(json, content_type='application/json;charset=utf-8')
It returns the single row in the data base:
[{"model": "sensors.sensor", "pk": 4, "fields": {"userid": 1, "update_date": "2019-03-09T19:15:58Z", "status": false, "name": "sidedoor", "zone": "firstfloor"}}]
Which does not work. What does "ajax.url" expect from the view?
This question has an accepted answers - jump to answer
This discussion has been closed.
Answers
Hi @daneboy55 ,
I'm not familiar with Django, but if it's getting data returned, albeit just a single row, then I'd say the URL aspect is working fine and the problem would be in the view or the script that accesses the database.
Hope that offers some help,
Cheers,
Colin
Thanks for the response Colin. Yeah, it needs to be solved in the view. I have this code which works, but it's a cludge. I'd like to see a better way of doing this.
My view now looks like this:
My dataTables init look like this:
My url.py file is:
In your first post you have this json response:
With this structure you have nested objects which can be accessed like this example:
https://datatables.net/examples/ajax/deep.html
Your
columns.data
config will look like this:I'm not familiar with Django but it looks like you second version of
Sensor_asJson
is doing some extra work. Looks like line 3 (serialized_objects = serializers.serialize('json', object_list)
) is creating a json string but then you are parsing the string back to a Python object in line 4. So I think object_list in line 2 and json_objects in line 4 are effectively the same.You might be able to re-write this code:
As this using list comprehension:
This is a long way of saying your second version could look like this to eliminate the nested objects:
Kevin
Thanks for the response. I did try and convert the queryset response to a list object with list(object_list) and then tried to iterate over the list to grab the "fields" values. I kept getting "Sensor object is not subscriptable". I get the same error with the listcomp.
Its hard to say without knowing what the sensor object contains. You might need to loop through it they way you have originally:
It sounds like you have an idea of what the data structure needs to be. You just need to get your Python code to create that structure Datatables supports. It will be hard for us to help with the Python side. But if you have questions please post them.
Kevin