[英]Remove duplication in python django_tables2
我正在使用django_tables2,并得到了以下两个几乎相同的表:
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()
如何删除/减少重复?
如果确实如此,则可以编写一个工厂为您动态创建Table
类:
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')
在此示例中,我不建议这样做。 您可能需要稍后更改两个表之一,即PITA。
另一种方法是在模型返回mapset_{}_edit
的正确值时采用某种方法。 然后,您可以只更改ButtonColumn
的实现,以向模型询问正确的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.