Custom columns in django_tables2

I had a search around this, but I didnโ€™t have much luck, so I was looking for a little help. I am trying to add some additional columns to the table defined by the model using function definitions in the model. This is what my code looks like:

# models.py
class MyModel(models.Model):
    my_field = models.TextField()

    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(....)

    class Meta:
        model = MyModel

# views.py
table = MyTable(MyModel.objects.all())
RequestConfig(request).configure(table)
return render(request, ....)

My question is: can I access the my_functionrecords passed to MyTableso that I can show the result my_functionin a user column my_extra_column? I suppose I need to use accessors, but I can't figure out how I can access the request data using this. Thank!

+4
source share
1 answer

, , :) , , , 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

, , MyModel. , ordering=False , order_by=('field', 'field2')

+3

All Articles