- alex/django-filter (doc)
- ソート条件を複数指定できるようにする
/events?o=opening_on&o=-title
/events?o=-presenter&o=-opening_on&o=title
順序フィルター: OrderingFilter
class EventFilter(django_filters.FilterSet):
# https://github.com/carltongibson/django-filter/blob/develop/docs/migration.txt
o = django_filters.OrderingFilter(
choices=(
('-opening_on', _('Opening On Desc')),
('opening_on', _('Openning On Asc')),
('-title', _('Title Desc')),
('title', _('Title Asc')),
('presenter', _('Presenter Asc')),
('-presenter', _('Presenter Desc')), ))
class Meta:
model = models.Event
テンプレートタグ: ordering
-
query
でクエリ文字列を返す -
direction
にasc
/desc
を返す
@register.assignment_tag(takes_context=True)
def ordering(context, field, key='o'):
qdict = context.get('request').GET.copy()
rfield = '-' + field
q = qdict.getlist(key)
if rfield in q:
q.remove(rfield)
direction = "asc"
else:
if field in q:
q.remove(field)
field = rfield
direction = "desc"
q = [field] + q
qdict.setlist(key, q)
return dict(query=qdict.urlencode(), direction=direction)
テンプレート:
{% load mytags %}
<thead>
<tr>
<th>
{% ordering 'opening_on' as opening_on_order %}
<a href="?{{ opening_on_order.query }}">
<span class="sort-{{ opening_on_order.direction }}">{% trans 'Opening On' %}</span></a></th>
<th>
{% ordering 'title' as title_order %}
<a href="?{{ title_order.query }}">
<span class="sort-{{ title_order.direction }}">{% trans 'Event Title' %}</span></a></th>
</tr>
</thead>
スタイル:
<style>
.sort-asc:after{content: "↓"}
.sort-desc:after{content: "↑"}
</style>