简体   繁体   中英

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. 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. 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().

The situation becomes complicated when we want to sort on calculated fields. In this case, it is best to disable serverSide operations in JavaScript

$.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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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