Custom columns in django_tables2

前端 未结 1 1641
灰色年华
灰色年华 2021-01-02 15:08

I\'ve had a search around for this but haven\'t had much luck so looking for a bit of help. I\'m trying to add some extra columns to a table defined by a model, using functi

相关标签:
1条回答
  • 2021-01-02 15:40

    I figured it out in the end, it was actually not too hard after all :) So using my example above, in order to add a custom column using a function in the associated model you just use accessors ...

    # models.py
    class MyModel(models.Model):
        my_field = models.TextField()
        my_field_2 = models.IntegerField()
    
        def my_function(self):
            # Return some calculated value based on the entry
            return my_value
    
    # tables.py
    class MyTable(tables.Table):
    
        my_extra_column = tables.Column(accessor='my_function',
             verbose_name='My calculated value')
    
        class Meta:
            fields = ['my_field', 'my_field_2', 'my_extra_column']
            model = MyModel
    

    The trouble comes if and when you want to be able to sort this data, because the function won't translate into any valid field in MyModel. So you could either disable sorting on this column using ordering=False or specify a set using order_by=('field', 'field2')

    0 讨论(0)
提交回复
热议问题