首页 > 代码库 > django + python + easyui datagrid

django + python + easyui datagrid

前台:

<table id="dg"></table>

 $(‘#dg‘).datagrid({
            url:‘/url/‘,

     columns:[[
                {field:‘Name‘,title:‘name‘,width:100},
                {field:‘User‘,title:‘user‘,width:100}

    ]]

})

后台:主要有3个参数,page(页数)、rows(每页行数)、total(总行数)

思路:

1、datagrid会自己传page 跟rows过来,直接在后台获取

2、得到page跟rows后把它们类型转为int、从数据库取出数据把总行数赋给total,然后把数据放到列表里面

3、判断page是不是第一页:

  3.1、如果是第一页:判断有多少行(rows),取rows行数据

  3.2、如果不是第一页:从列表删除page-1条数据得到剩余的数据,然后再做第3.1步

4、把total跟得到的数据拼起来:ealist = {‘rows‘:alist,‘total‘:total}

5、把ealist转成json格式数据return回去, ok

def userlist(request):
    page = request.GET[‘page‘]
    rows = request.GET[‘rows‘]
    User_list = Userdb.objects.all().order_by(‘-id‘)
    alist=[]
    for i in User_list.values():
        alist.append(i)
    tl = len(alist)
    easy_list = []
    rs = rows
    a = int(page)-1
    b = int(rs)
    total = json.dumps(tl)
    if (a==0):
        a = 1
        if(b>len(alist)):
            ealist = {‘rows‘:alist,‘total‘:total}
        else:
            for s in range(a*b):
                easy_list.append(alist[s])
            ealist = {‘rows‘:easy_list,‘total‘:total}
    else:
        for s in range(a*b):
            print len(alist)
            del alist[0]
            print alist
        if(len(alist)<b):
            ealist = {‘rows‘:alist,‘total‘:total}
        else:
            for i in range(a*b):
                easy_list.append(alist[i])
            ealist = {‘rows‘:easy_list,‘total‘:total}
    easylist = json.dumps(ealist,cls=CJsonEncoder)
    return HttpResponse(easylist)

//如果数据里面有时间的话,使用json.dumps()会出错。下面这个函数就是处理这个问题

class CJsonEncoder(json.JSONEncoder):
    def default(self, obj):
        try:
            if isinstance(obj, datetime):
                 return obj.struct_time(‘%Y-%m-%d %H:%M:%S‘)
            elif isinstance(obj, date):
                da = str(obj.strftime(‘%Y-%m-%d‘))
                #return obj.strftime(‘%Y-%m-%d‘)
                return da
            else:
                return json.JSONEncoder.default(self, obj)
        except Exception,e:
            print e

 

django + python + easyui datagrid