Search code examples
pythondjangodjango-tables2

Custom rendering of nested field in django-tables2


I have a table defined like this, where I want to apply custom rendering for a field:

import django_tables2 as tables

class SetTable(tables.Table):
    class Meta:
        model = Set
        fields = (
             "series.title",
        )

    def render_series_title(self, value):
        return 'x'

For simple fields on the object itself (i.e. without a period) this works. But when there is a nested relationship (in this case, the Set model has a foreign key relationship to Series, and I want to display the Title field from the series), the custom rendering is not triggered. I have tried render_title, render_series_title, render_series__title, etc., and none of these gets called.

The table is specified as the table_class in a django_filters view, and is displaying the data fine, except that it is using the default rendering and bypassing the custom rendering function.

What am I missing?


Solution

  • You can use accessor for that:

    import django_tables2 as tables
    
    class SetTable(tables.Table):
         series_title = tables.Column(accessor='series.title')  # or newer version series__title
         class Meta:
            model = Set
            fields = (
                 "series_title",
            )
    

    Unfortunately, I did not find where to see the documentation for it (there is some indication of accessor here), but I checked the source code about Column and Accessor classes.