A basic view for working with jQuery dataTables plugin

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
from django.http import HttpResponse
from django.db.models import Q, CharField

import json
from cStringIO import StringIO

def datatables_view(request):
    objects = MyModel.objects.all()
    list_display = ['field1', 'field2', ...]
    list_filter = [f.name for f in MyModel._meta.fields if isinstance(f, CharField)] #a simple way to bring all CharFields, can be defined in specifics

    # count total items:
    iTotalRecords = objects.count()

    #filter on list_filter using __contains
    search = request.GET['sSearch']
    queries = [Q(**{f+'__contains' : search}) for f in list_filter]
    qs = reduce(lambda x, y: x|y, queries)
    objects = objects.filter(qs)

    #sorting
    order = dict( enumerate(list_display) )
    dirs = {'asc': '', 'desc': '-'}
    ordering = dirs[request.GET['sSortDir_0']] + order[int(request.GET['iSortCol_0'])]
    objects = objects.order_by(order_by)

    # count items after filtering:
    iTotalDisplayRecords = objects.count()


    # finally, slice according to length sent by dataTables:
    start = int(request.GET['iDisplayStart'])
    length = int(request.GET['iDisplayLength'])
    objects = objects[ start : (start+length)]
    
    # extract information
    data = [map(lambda field: getattr(obj, field), list_display) for obj in objects]

    #define response
    response = {
        'aaData': data,
        'iTotalRecords': iTotalRecords,
        'iTotalDisplayRecords': iTotalDisplayRecords,
        'sEcho': request.GET['sEcho']
    }

    #serialize to json
    s = StringIO()
    json.dump(response, s)
    s.seek(0)
    return HttpResponse(s.read())

More like this

  1. Test Django against many Pythons and databases by jacobian 7 years, 1 month ago
  2. Binding signals to abstract models by andreterra 1 year, 11 months ago
  3. pavement file for deploying django projects by bl4th3rsk1t3 4 years, 11 months ago
  4. GeoDjango maps in admin TabularInlines by alanB 3 years, 6 months ago
  5. Variable._resolve_lookup monkeypatch by showell 4 years, 5 months ago

Comments

(Forgotten your password?)