将相关模型的方法放入jqgrid的单独列中

时间:2012-03-24 20:12:21

标签: django orm jqgrid

我在jqgrid包中使用django 1.4和django_gems 以下代码尝试通过连接名字和姓氏将virtual列引入grid

然而它失败了

  

无法将关键字client__get_fullname解析为字段。

有没有可以接受的方法来实现这个目标?

 class Car(models.Model):
     number = models.CharField(max_length = 50)
 client = models.ForeignKey('Client')

 class Client(models.Model):
     first_name = models.CharField(max_length = 50)
 last_name = models.CharField(max_length = 50)
 def get_fullname(self):
     return '%s %s' % (self.first_name, self.last_name)

 from django_gems.jqgrid
 import JqGrid
 class CarGrid(JqGrid):
     queryset = Car.objects.all()
 fields = ['number', 'client__get_fullname']

 jqgrid config = {
     "altRows": true,
     "rowList": [10, 25, 50, 100],
     "sortname": "id",
     "viewrecords": true,
     "autowidth": false,
     "forcefit": false,
     "shrinkToFit": false,
     "height": "auto",
     "colModel": [{
         "index": "id",
         "editable": false,
         "name": "id",
         "label": "ID"
     }, {
         "index": "number",
         "editable": false,
         "name": "number",
         "label": "number"
     }, {
         "index": "first_name",
         "editable": false,
         "name": "client__first_name",
         "label": "first name"
     }],
     "caption": "Cars",
     "datatype": "json",
     "gridview": true,
     "sortorder": "asc",
     "viewsortcols": true,
     "url": "main/examplegrid",
     "rowNum": 10,
     "pager": "#pager",
     "jsonReader": {
         "repeatitems": false
     }
 }

 sample data = {
     "total": 1,
     "records": 1,
     "rows": [{
         "client__first_name": "Bill",
         "client__last_name": "Clinton",
         "id": 1,
         "number": "111222"
     }],
     "page": 1
 }

1 个答案:

答案 0 :(得分:2)

OK!让我们来获取JSON数据

{
    "total": 1,
    "records": 1,
    "rows": [
        {
            "client__first_name": "Bill",
            "client__last_name": "Clinton",
            "id": 1,
            "number": "111222"
        }
    ],
    "page": 1
}

并且jqGrid包含一个附加列

{name: "client__full_name", label: "full name"}

应该从client__first_nameclient__last_name构建。在这种情况下,最简单的方法是使用beforeProcessing回调函数:

$("#list").jqGrid({
    url: "main/examplegrid",
    datatype: "json",
    colModel: [
        {name: "id", label: "ID"},
        {name: "client__first_name", label: "first name"},
        {name: "client__last_name", label: "last name"},
        {name: "client__full_name", label: "full name"}
    ],
    gridview: true,
    jsonReader: { repeatitems: false },
    //... other parameters
    beforeProcessing: function (data) {
        var items = data.rows, n = items.length, i, item;
        for (i = 0; i < n; i++) {
            item = items[i];
            item.client__full_name = item.client__first_name + ' ' +
                item.client__last_name;
        }
    }
});

在从服务器接收数据之后和处理数据之前,jqGrid将调用回调函数beforeProcessing。因此,我们可以通过简单的方式实现任何“虚拟”列。