django_tables2中的自定义列

时间:2016-03-07 09:27:28

标签: django django-tables2

我已经搜索过这个但是没有多少运气,所以寻求一些帮助。我正在尝试使用模型中的函数定义向模型定义的表添加一些额外的列。这是我的代码现在的样子:

# 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_function的条目中访问MyTable,以便在自定义my_function列中显示my_extra_column的结果?我假设我需要使用访问器,但我无法看到如何使用它来访问查询集数据。谢谢!

1 个答案:

答案 0 :(得分:7)

我最终想通了,毕竟实际上并不太难:) 因此,使用上面的示例,为了使用关联模型中的函数添加自定义列,您只需使用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')

指定一个集合
相关问题