disable ordering by default for django_tables2 Tables
Asked Answered
H

3

5

I use django_tables2 to render my tables. For one table, I only want to see the most recent 5 entries. Therefore, I need to order my queryset before passing it to the table object:

qset = myObject.objects.order_by('-start_time').all()[:5]
table = MyTableClass(qset, template='path/to/template.html')

This yields the following error message:

AssertionError: Cannot reorder a query once a slice has been taken.

I could set orderable=False for every django_tables.Column, but since MyTableClass inherits from another table class, I would like to avoid this.

Thanks in advance

Hosiery answered 17/11, 2017 at 14:45 Comment(0)
H
11

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

So this solves my Problem:

class MyTableClass(django_tables2.Table):
    class Meta:
        orderable = False
    ...

Update: As mentioned by @Jieter in the comments, passing it as an argument should also work (didn't check that):

table = MyTable(data, orderable=False)
Hosiery answered 17/11, 2017 at 16:3 Comment(1)
Note that it's also available as an argument to the constructor, table = MyTable(data, orderable=False) will disable ordering for a table. This takes precedence over any value set in the class Meta.orderable attribute.Acrylic
E
1

You could use __in to select the most recent entries:

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')
Ebarta answered 17/11, 2017 at 14:53 Comment(1)
This works, though I'd like to avoid a second query and solve it by configuring the django_tables2.Table object (if possible).Hosiery
W
-3

Try changing to this.

qset = myObject.objects.all().order_by('-start_time')[:5]
Whitehot answered 17/11, 2017 at 14:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.