标签:
jQuery DataTables
本文参考的官方示例
关于Python序列化
Django中的Models序列化
Python的super用法
models.py
from django.db import models from django.contrib import admin # Create your models here. class BankData(models.Model): acc_no = models.CharField(max_length=45,primary_key=True) name = models.CharField(max_length=45,blank=True,default=‘‘) bank = models.CharField(max_length=45,blank=True,default=‘‘) class BankDataAdmin(admin.ModelAdmin): list_display = (‘acc_no‘,) admin.site.register(BankData, BankDataAdmin)
serializers.py
from rest_framework import serializers from myapp.models import BankData class BankDataSerializer(serializers.ModelSerializer): class Meta: model = BankData fields = (‘acc_no‘,‘name‘,‘bank‘)
views.py
#! /usr/bin/env python # -*- coding:utf-8 -*- from myapp.models import BankData from django.http import HttpResponse from myapp.serializers import BankDataSerializer from rest_framework.renderers import JSONRenderer #json class JSONResponse(HttpResponse): def __init__(self, data, **kwargs): content = JSONRenderer().render(data) kwargs[‘content_type‘] = ‘application/json‘ super(JSONResponse, self).__init__(content,**kwargs) #jsonp class JSONPResponse(HttpResponse): def __init__(self, data, callback=‘callback‘,**kwargs): content = JSONRenderer().render(data) jsonp_content = "(" + callback+ "(" + content + ")" kwargs[‘content_type‘] = ‘application/json‘ super(JSONPResponse, self).__init__(jsonp_content,**kwargs) #json for DataTables class JSONDTResponse(HttpResponse): def __init__(self, data, **kwargs): content = JSONRenderer().render(data) dt_content = "{\"data\":" + content + "}" kwargs[‘content_type‘] = ‘application/json‘ super(JSONDTResponse, self).__init__(dt_content,**kwargs) def datas(request): bds = BankData.objects.all() serializer = BankDataSerializer(bds,many=True) return JSONDTResponse(serializer.data)
bank_data.html
<!DOCTYPE html> <head> <title>银行信息</title> <link rel="stylesheet" type="text/css" href="/static/css/jquery.dataTables.min.css"> <script type="text/javascript" src="/static/js/jquery.js"></script> <script type="text/javascript" src="/static/js/jquery.dataTables.min.js"></script> </head> <body> <script> $(document).ready(function() { $(‘#example‘).dataTable( { "bProcessing":true, "ajax":‘/myapp/datas/‘, "columns": [ {‘data‘:‘acc_no‘}, {‘data‘:‘name‘}, {‘data‘:‘bank‘}, ] }); }); </script> <table id="example" class="display" cellspacing="0" width="100%"> <thead> <tr> <th>账号</th> <th>姓名</th> <th>银行</th> </tr> </thead> <tfoot> <tr> <th>账号</th> <th>姓名</th> <th>银行</th> </tr> </tfoot> </table> </body>
jQuery DataTables && Django serializer
标签:
原文地址:http://www.cnblogs.com/flowjacky/p/4537408.html