默认情况下禁用 django_tables2 表的排序
disable ordering by default for django_tables2 Tables
我使用 django_tables2 渲染我的 table。对于一个 table,我只想查看最近的 5 个条目。因此,我需要在将查询集传递给 table 对象之前对其进行排序:
qset = myObject.objects.order_by('-start_time').all()[:5]
table = MyTableClass(qset, template='path/to/template.html')
这会产生以下错误消息:
AssertionError: Cannot reorder a query once a slice has been taken.
我可以为每个 django_tables.Column
设置 orderable=False
,但由于 MyTableClass 继承自另一个 table class,我想避免这种情况。
提前致谢
试试改成这个。
qset = myObject.objects.all().order_by('-start_time')[:5]
您可以使用 __in
到 select 最近的条目:
most_recent = list(myObject.objects.order_by('-start_time').all()[:5].values_list('pk', flat=True)) # list is required if databases does not support LIMIT in subqueries
qset = myObject.objects.filter(id__in=most_recent).order_by('-start_time')
发件人:http://django-tables2.readthedocs.io/en/latest/pages/api-reference.html#table-meta
orderable (bool): Default value for column’s orderable attribute.
If the table and column don’t specify a value, a column’s orderable value will fallback to this. This provides an easy mechanism to disable ordering on an entire table, without adding orderable=False to each column in a table.
所以这解决了我的问题:
class MyTableClass(django_tables2.Table):
class Meta:
orderable = False
...
更新:
正如@Jieter 在评论中提到的,将其作为参数传递也应该有效(未检查):
table = MyTable(data, orderable=False)
我使用 django_tables2 渲染我的 table。对于一个 table,我只想查看最近的 5 个条目。因此,我需要在将查询集传递给 table 对象之前对其进行排序:
qset = myObject.objects.order_by('-start_time').all()[:5]
table = MyTableClass(qset, template='path/to/template.html')
这会产生以下错误消息:
AssertionError: Cannot reorder a query once a slice has been taken.
我可以为每个 django_tables.Column
设置 orderable=False
,但由于 MyTableClass 继承自另一个 table class,我想避免这种情况。
提前致谢
试试改成这个。
qset = myObject.objects.all().order_by('-start_time')[:5]
您可以使用 __in
到 select 最近的条目:
most_recent = list(myObject.objects.order_by('-start_time').all()[:5].values_list('pk', flat=True)) # list is required if databases does not support LIMIT in subqueries
qset = myObject.objects.filter(id__in=most_recent).order_by('-start_time')
发件人:http://django-tables2.readthedocs.io/en/latest/pages/api-reference.html#table-meta
orderable (bool): Default value for column’s orderable attribute.
If the table and column don’t specify a value, a column’s orderable value will fallback to this. This provides an easy mechanism to disable ordering on an entire table, without adding orderable=False to each column in a table.
所以这解决了我的问题:
class MyTableClass(django_tables2.Table):
class Meta:
orderable = False
...
更新: 正如@Jieter 在评论中提到的,将其作为参数传递也应该有效(未检查):
table = MyTable(data, orderable=False)