attrgetter
Shortcut for supplying an operator.attrgetter
-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.attrgetter
directly.
This helper must be called inline with the column definition, in order to provide the attribute to read from the column value. It will returned a stand-in callback to defer the attribte lookup until the callback is needed.
helpers.attrgetter
can be used to read an attribute from the target value. The
utility of this is mostly in the ability to specify your database fields for the column but
still use a model method to actually supply the data in question. For example, if an address
is to be displayed in a table column, supplying the model's get_address
method as
the "field" for the column would lose you the database field list, so database-level searching
and sorting would not be possible. Instead, you can supply your field list and then have the
presentational callback deferred to a model method:
import operator datatable_options = { 'columns': [ # Standard use; must call the helper once to give it the attribute to read ("Address", ['street', 'city', 'state', 'zipcode'], helpers.attrgetter('get_address'), # Better perhaps to use the through_filter() helper ("Address", ['street', 'city', 'state', 'zipcode'], helpers.through_filter(operator.attrgetter('get_address')), ], }
Using this helper in custom callbacks provides no tangible benefit over getting the attribute from the target value yourself, but can still be done:
def get_column_Address_data(self, instance, *args, **kwargs): # Generate the real callback helper, then call it callback = helpers.attrgetter('get_address') return callback(instance) # This is equivalent real Python code, and better for readability return instance.get_address()