I hinted previously that the "data" column option is unfortunately
slightly overloaded.
The original problem that needed solving was that one might have a
model field that should be exposed under a different, maybe more
"pretty", column name, e.g. "published_at" as "date".
The "name" option does exactly that:
published_at = Column(name="date")
"published_at" is now exposed as "date".
However, in a more complex scenario, one might want to expose a field
from a related model - say the "author" column is actually
"
issue.writer.name". One would have to write:
issue__writer__name = Column(name="author")
Which is of course somewhat ugly. So I additionally added the "data"
attribute, which basically was supposed to work like "name" in
reverse:
author = Column(data="issue__writer__name")
Now "issue__writer__name" is exposed as "author".
The ability to make "data" a callable was added afterwards on top of
that. Of course, we now have the dilemma: Because ordering is based on
the Django ORM, and the Django ORM can only sort on model fields, not
arbitrary callables (whether they are model methods or not), table
columns that use a callable "data" could no longer be sortable. The
callable would still be used for display of the cell, but not for
ordering.
Now, you *should* be able to specify a callable both as a string AND a
function object. You mentioned that the latter works for you. The
former works for me as well:
class MyModel(models.Model):
...
def get_priority(self):
return "foo"
class MyTable(tables.Table):
priority = tables.Column(data='get_priority')
table = MyTable(MyModel.objects.all())
print table.rows[0]['priority']
# => prints "foo"
Ok, so here's where I think the confusion stems from:
I mentioned that once you make a columns "data" option a callable,
that column is no longer sortable. As a matter of fact, that is not
entirely true. There is an exception to this rule (see also
test_models.py:269+): If "data" is a callable, and the column
otherwise refers to a valid model field name, then that field name
will be used for ordernig, and the column actually remains sortable.
So for example:
author = table.Columns(data=get_author)
If "author" is a valid field of the model, the column can be sorted.
Otherwise, it can't.
Unfortunately though, that only works if you specify a function
object. If you specify the callable as a string, the column will be
unsortable in any case. Whether or not that should be otherwise could
potentially be argued, but I think it probably should. I opened a
ticket for the issue.
I hope I wasn't too confusing. The short version is: Callables should
work both given as a string and a callable object, but only in the
latter will the column be sortable.
Michael