Django-tables2:如何使用order_by访问器

用户名

假设我们有一列,例如:

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

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

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

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

鲁德拉

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

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

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

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

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

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使用的例子

#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

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章