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 function definitions in the model. Here's what my code looks like now:
# 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 my_function
in the entries passed to MyTable
so I can show the result of my_function
in the custom my_extra_column
column? I assume I need to be using accessors, but I can't see how I can access the queryset data using this. Thanks!
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 ...
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 usingordering=False
or specify a set usingorder_by=('field', 'field2')