在django-tables2中,是否有一种方法可以始终按特定列对表进行排序?
我正在使用在django-tables2中,是否有一种方法可以始终按特定列对表进行排序?,django,django-tables2,Django,Django Tables2,我正在使用django-tables2来呈现MyModel的表格MyModel的category字段指定了几个不同的类别。我希望能够通过覆盖order\u,以便表的主顺序始终是category,而选择的任何其他内容都只是次顺序。有什么建议吗?论坛来晚了。我还没有尝试下面的方法。但我想这可能会有所帮助。在tables.py中创建一个表。并像往常一样将该表添加到视图中。通过添加的表,您可以尝试在django-tables2中支持的order_ **tables.py** import django
django-tables2
来呈现MyModel
的表格MyModel
的category
字段指定了几个不同的类别。我希望能够通过覆盖order\u,以便表的主顺序始终是category
,而选择的任何其他内容都只是次顺序。有什么建议吗?论坛来晚了。我还没有尝试下面的方法。但我想这可能会有所帮助。在tables.py中创建一个表。并像往常一样将该表添加到视图中。通过添加的表,您可以尝试在django-tables2中支持的order_
**tables.py**
import django_tables2 as tables
from .models import Person
class PersonTable(tables.Table):
class Meta:
model = Person
template_name = 'django_tables2/bootstrap.html'
**views.py**
from django.shortcuts import render
from django_tables2 import RequestConfig
from .tables import PersonTable
def people_listing(request):
config = RequestConfig(request)
table = PersonTable(Person.objects.all())
table.order_by = 'name'
return render(request, 'data/person.html', {'table': table})
对于其他有这个问题的人,我最终得到了一个答案:
class PersonTable(tables.Table):
def __init__(self, *args, **kwargs):
def generate_order_func(field_name: str) -> Callable:
# django-tables2 stamps any secondary ordering if you have a custom ordering function on any of your
# ordering fields. This adds custom ordering to every field so that name is always the primary
# ordering
def order_func(qs: QuerySet, descending: bool) -> Tuple[QuerySet, bool]:
# Need custom ordering on deal_state (not alphabetical)
qs = qs.order_by("name", ("-" if descending else "") + field_name)
return qs, True
return order_func
for field in self._meta.fields:
setattr(self, f"order_{field}", generate_order_func(field))
super().__init__(*args, **kwargs)
这将覆盖每个字段的排序,使其由主排序第一个字段排序 感谢您提供这段代码片段,它可能会提供一些有限的、即时的帮助。通过展示为什么这是一个很好的问题解决方案,A将极大地提高它的长期价值,并将使它对未来有其他类似问题的读者更有用。请在您的答案中添加一些解释,包括您所做的假设。对不起,这并不能解决此问题。这将使表最初按“名称”排序,但当您要对其他类别进行排序时,不会将其作为主要排序