简体   繁体   English

使用 django-datatables-view 对自定义列进行排序

[英]Sorting custom columns with django-datatables-view

Using Django 3, python 3.6, django-datatable-view 1.19.1 Trying to do a datatable with columns from my model and computed before output ones. Using Django 3, python 3.6, django-datatable-view 1.19.1 Trying to do a datatable with columns from my model and computed before output ones. I draw all values that I needed but after trying to sort custom column getting an error:我绘制了我需要的所有值,但在尝试对自定义列进行排序后出现错误:

Cannot resolve keyword 'XXXX' into field. Choices are: ...

I've found a way to register a column as virtual column, without db source, but it was in django-datatable-view 0.5.4 docs but those ways don't work anymore.我找到了一种将列注册为虚拟列的方法,没有数据库源,但它在 django-datatable-view 0.5.4 文档中,但这些方法不再起作用。 In last version documentation links with info that I need are unavailable.在最新版本的文档链接中,我需要的信息不可用。

Please, help me to figure out, how can I deal with custom computed columns from my model's fields( sort, render )请帮我弄清楚,如何处理来自模型字段的自定义计算列(排序,渲染)

This is a little tricky now.现在这有点棘手。

To define computed fields:要定义计算域:

class ListJson(BaseDatatableView):

columns = ["id", "status_code", "computed_field"]
order_columns = ["id", "status_code"]

# Override render_column method
def render_column(self, row, column):
    if column == "computed_field":
        return row.computed_field()
    else:
        return super(ListJson, self).render_column(row, column)

This allows you to return the computed_field method value().这允许您返回 computed_field 方法 value()。

The situation becomes complicated when we want to sort on calculated fields.当我们要对计算字段进行排序时,情况就变得复杂了。 In this case, it is best to disable serverSide operations in JavaScript在这种情况下,最好在 JavaScript 中禁用 serverSide 操作

$.extend($.fn.dataTable.defaults, {
    serverSide: false,
});

However, you will then have to return all the lines at once, which can kill the server.但是,您必须立即返回所有行,这可能会杀死服务器。

If you want to sort on the backend side, you need to arrange and return the appropriate queryset with a virtual field.如果要在后端进行排序,则需要安排并返回带有虚拟字段的相应查询集。

class ListJson(BaseDatatableView):
      def get_initial_queryset(self):
            return qs

Just build your query like THIS .只需像这样构建您的查询

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM