Search code examples
pythondjangodjango-tables2

Remove duplication in python django_tables2


I'm using django_tables2, and have ended up with the following two tables which are almost identical:

class UserMapsetTable(Table):

    edit = ButtonColumn('Edit', 'mapsets_users_edit')
    mappings = ButtonColumn('Mappings', 'mapsets_users_mappings')

    class Meta:
        model = UserMappingRuleSet
        fields = (
            'name', 
            'notes'
        )
        attrs = responsive_table_attrs()


class ReadingMapsetTable(Table):

    edit = ButtonColumn('Edit', 'mapsets_readings_edit')
    mappings = ButtonColumn('Mappings', 'mapsets_readings_mappings')

    class Meta:
        model = ReadingMappingRuleSet
        fields = (
            'name', 
            'notes'
        )
        attrs = responsive_table_attrs()

How do I remove/reduce the duplication?


Solution

  • If they really are this similar, you could write a factory to dynamically create the Table classes for you:

    def table_factory(Model, name):
        class Table(tables.Table)
    
            edit = ButtonColumn('Edit', 'mapsets_' + name + '_edit')
            mappings = ButtonColumn('Mappings', 'mapsets_' + name + '_mappings')
    
            class Meta:
                model = Model
                fields = (
                    'name', 
                    'notes'
                )
                attrs = responsive_table_attrs()
        return Table
    
    UserMapsetTable = table_factory(UserMappingRuleSet, 'users')
    ReadingMapsetTable = table_factory(ReadingMapRuleSet, 'readings')
    

    In this example, I would not advise doing this. You probably need changing one of the two tables later which will be a PITA.

    Another way would be to have some method on the model's returning the right value for mapset_{}_edit. Then you could just change the implementation of your ButtonColumn to ask the model for the correct value.