Django与ListView反向排序

时间:2016-08-20 20:19:25

标签: python django python-3.x listview django-views

我已经在通用ListView中实现了排序:

$ifExists = DB::table('characters')->where('userid', Auth::id())->exists();

if($ifExists){
    return Redirect('/board');
}else{
    return view('intro');
}

在我的模板中:

class CarList(LoginRequiredMixin, ListView):
    model = Car
    paginate_by = 30

    ordering = 'car_id_internal'

    def get_ordering(self):
        return self.request.GET.get('ordering', 'car_id_internal')

    def get_context_data(self, *args, **kwargs):
        context = super(CarList, self).get_context_data(*args, **kwargs)
        context['current_order'] = self.get_ordering()
        return context

这样可以正常工作,但我希望用户能够在再次单击列标题时将顺序从升序转换为降序。 Django有可能吗?我正在使用Django 1.9。

我希望有人可以提供帮助。

1 个答案:

答案 0 :(得分:4)

您需要使用另一个变量来确定asc / desc排序。根据当前选择的模板,模板应交替链接。在视图中,您在字段名称之前按adding a dash反转排序。请尝试以下方法:

class CarList(ListView):
    model = Car
    paginate_by = 30

    ordering = 'car_id_internal'
    def get_ordering(self):
        self.order = self.request.GET.get('order', 'asc')
        selected_ordering = self.request.GET.get('ordering', 'car_id_internal')
        if self.order == "desc":
            selected_ordering = "-" + selected_ordering
        return selected_ordering

    def get_context_data(self, *args, **kwargs):
        context = super(CarList, self).get_context_data(*args, **kwargs)
        context['current_order'] = self.get_ordering()
        context['order'] = self.order
        return context

模板:

<table>
<tr>
    <th><a href="{% url 'car_list' %}?ordering=car_id_internal&order={% if order == 'desc' %}asc{% else %}desc{% endif %}">Internal car ID</a></th>
    <th><a href="{% url 'car_list' %}?ordering=type&order={% if order == 'desc' %}asc{% else %}desc{% endif %}">Type</a></th>
    <th><a href="{% url 'car_list' %}?ordering=brand&order={% if order == 'desc' %}asc{% else %}desc{% endif %}">Brand</a></th>
</tr>
{% for car in object_list %}
<tr>
    <td>{{car.id}}</td>
    <td>{{car.type}}</td>
    <td>{{car.brand}}</td>
</tr>
{% endfor %}