itemgetter

Columns from demo: Body Text (as a slice)

Shortcut for supplying an operator.itemgetter-type callback, but which accepts the additional arguments that DatatableView provides by default.

This helper's usefulness is supplanted by the helpers.through_fitler callback, which allows you to use operator.itemgetter directly.

This helper must be called inline with the column definition, in order to provide the item to get from the column value. It will returned a stand-in callback to defer the item-getting until the callback is needed.

helpers.itemgetter can be used to fetch a specific item or slice from a value. It includes the option to specify an ellipsis keyword argument, which, if provided along with a slice against a string, will be appended to a sliced string.

import operator
datatable_options = {
    'columns': [
        # Standard use; must call the helper once to give it the item to access
        ("Body Text", 'body_text', helpers.itemgetter(slice(0, 30)),
        # Better perhaps to use the through_filter() helper
        ("Body Text", 'body_text', helpers.through_filter(operator.itemgetter(slice(0, 30)),

        # Append an ellipsis
        ("Body Text", 'body_text', helpers.itemgetter(slice(0, 30), ellipsis="..."),
        # Again, better perhaps to use the through_filter() helper with the truncatechars filter
        ("Body Text", 'body_text', helpers.through_filter(truncatechars(30)),
    ],
}

Using this helper in custom callbacks provides no tangible benefit over getting an item or slice from the target value yourself, but can still be done:

def get_column_Body_Text_data(self, instance, *args, **kwargs):
    # Generate the real callback helper, then call it
    callback = helpers.itemgetter(slice(0, 30))
    return callback(kwargs['default_value'])
    
    # This is equivalent real Python code, and better for readability
    return kwargs['default_value'][:30]