Django-tables2:如何使用order_by访问器 [英] Django-tables2: how to order_by accessor

查看:66
本文介绍了Django-tables2:如何使用order_by访问器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有一列,例如:

Say we have a column like:

num_member = tables.Column(accessor = 'members.count', verbose_name = 'number of members' )

当我尝试在模板中对它进行排序时,它会引发:

When I tried to sort this in the template, it raises:

Field Error: Cannot resolve keyword u'count' into field

我阅读了文档,并说我们可以通过传入某种 accessor 来使用 order_by ,但是请问究竟如何做到这一点?

I read the document and it says we can use order_by by passing in some sort of accessor, but how exactly do we do this please?

推荐答案

对于类似于Model的property方法的函数,您可以使用 accessor 直接访问它.例如:

For function like Model's property method, you can access it directly using accessor. For example:

Class MyModel(models.Model):
    data= models.CharField(max_length=255)

    @property
    def print_function(self):
       return 'hello world'

#Table class
class MyTable(tables.Table):
        data= tables.Column(accessor='print_function')

    class Meta:
        model = MyModel
        fields = ('data')

使用上述方法,您可以使用访问器在表中显示不同种类的数据:

Using the above method, you can show different kinds of data in table using accessor:

Class SomeModel(models.Model):
    some_data= models.CharField(max_length=255)
    data= models.ManyToManyField(MyModel)

    @property
    def count_function(self):
       some_data= self.data.objects.count() #returns count of the objects
       return some_data

#Table class
class SomeTable(tables.Table):
    data= tables.Column(accessor='count_function')

    class Meta:
        model = SomeModel
        fields = ('data')

访问器可用于直接访问相关外键模型的字段值,例如:

And accessor can be used for directly accessing related foreignkey model's field value like:

Class SomeModel(models.Model):
    somedata= models.ForeignKey(MyModel)


#Table class
class MyTable(tables.Table):
        data= tables.Column(accessor='somedata.data')

    class Meta:
        model = SomeModel
        fields = ('data')

编辑

让我们举一个例子说明如何使用 order_by :

Lets give an example of how order_by can be used:

#Class Based view, I am subclassing ListView and SingleTableView here for example

class MyView(ListView, SingleTableView):
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['table'].order_by = '-last_updated' #last_updated is a datetimefield in model
        return context

在上面的代码中,我所做的是,我正在更改上下文中表数据的顺序,该顺序稍后将在模板中呈现.

In the above code, what I have done is that, I am changing the order of the table data in context which will later be rendered in template.

这篇关于Django-tables2:如何使用order_by访问器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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