Taking a linked model method in a separate jqgrid column

I am using django 1.4 along with jqgrid from the django_gems package. The following code tries to bring a "virtual" column to the grid by combining the first and last name. However, the failure "Cannot resolve the keyword" client__get_fullname "in the field."

Is there an acceptable way to achieve this?

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
source share
1 answer

OK! Let us get the JSON data.

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

and jqGrid contains an extra column

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

which should be built from client__first_name and client__last_name . In fact, the easiest way would be to use the beforeProcessing function:

 $("#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; } } }); 

The beforeProcessing callback function will be called by jqGrid after the data has been received from the server and before the data has been processed. Thus, we can implement any "virtual" column.

+2
source

Source: https://habr.com/ru/post/971216/


All Articles