django_tables2中的自定义列 [英] Custom columns in django_tables2

查看:41
本文介绍了django_tables2中的自定义列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经搜索了此内容,但是运气不太好,因此需要一些帮助。我正在尝试使用模型中的函数定义在模型定义的表中添加一些额外的列。这是我的代码现在的样子:

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_function 传递给 MyTable 的条目中,这样我就可以在自定义中显示 my_function 的结果 my_extra_column 列?我假设我需要使用访问器,但看不到如何使用此访问器访问查询集数据。谢谢!

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

# 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

如果您希望对数据进行排序的话,就会出现ble,因为该函数不会转换为 MyModel 中的任何有效字段。因此,您可以使用 ordering = False 禁用此列的排序,也可以使用 order_by =('field','field2')指定一个集合code>

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')

这篇关于django_tables2中的自定义列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆