我很久以前读过这个很棒的社区的第一篇文章:)
我在使用这个很棒的库“django-tables2”时遇到了问题。当我通过CharField对列进行排序时,它会执行区分大小写的排序,从而导致意外行为,如下所示:
Iago
Pablo
iago
我希望以更自然的方式订购:
Iago
iago
Pablo
这是我的简化代码:
class Inquiry(models.Model):
...
contact_last_name = models.CharField(max_length=50)
...
class Hometable(tables.Table):
contact_last_name = tables.Column(verbose_name="Contact", order_by=('contact_last_name'))
class Meta:
model = Inquiry
fields= ('contact_last_name',)
我知道在Django 1.8中有一个内置函数Lower来制作一个不敏感的order_by,但它不适用于django表:
contact_last_name = tables.Column(verbose_name="Contact", order_by=(Lower('contact_last_name')))
导致异常:
TypeError at /
'Lower' object is not iterable
有没有人用django-tables2做过类似的事情?
谢谢!
更新:解决方案是在视图中使用小写字段进行注释,然后可以在表中按顺序进行注释。
class Inquiry(models.Model):
...
contact_last_name = models.CharField(max_length=50)
...
class Hometable(tables.Table):
contact_last_name = tables.Column(verbose_name="Contact", order_by=('contact_last_name_lower'))
class Meta:
model = Inquiry
fields= ('contact_last_name',)
在将表配置为Alasdair目的时,在查询集中进行正确的注释:
inquiries = inquiries.annotate(contact_last_name_lower=Lower('last_name'))
my_table = Hometable(inquiries)
答案 0 :(得分:0)
我没有尝试过这个,我对django-tables2并不熟悉,所以我不知道它是否会起作用。
您可以尝试使用新的字段名称,例如为列设置contact_last_name_lower
时order_by
。
class Hometable(tables.Table):
contact_last_name = tables.Column(verbose_name="Contact", order_by=('contact_last_name_lower',))
class Meta:
model = Inquiry
fields= ('contact_last_name',)
然后,在实例化表时,使用小写字段注释查询集。
queryset = Inquiry.objects.annotate(contact_last_name_lower=Lower('contact_last_name'))
table = Hometable(queryset)
答案 1 :(得分:0)
Based on https://django-tables2.readthedocs.io/en/latest/pages/ordering.html#table-order-foo-methods you need to add a table.order_FOO() method
and end up with something like this:
class Hometable(tables.Table):
contact_last_name = tables.Column(verbose_name="Contact", order_by=('contact_last_name'))
def order_contact_last_name (self, QuerySet, is_descending):
QuerySet = QuerySet.annotate(
field_lower=Func(F('contact_last_name '), function='LOWER')
).order_by(('-' if is_descending else '') + 'field_lower')
return (QuerySet, True)
class Meta:
model = Inquiry
fields= ('contact_last_name',)
This should work when you click column headers to order as well as the initial ordering.