magu2
magu2

Reputation: 113

How to sort by within a Django list

This is a list of jobs and their prices. I need help on the sorting. I want to make it so that when you click on sort by Budget, the list is ordered by budget decreasing, and when clicked again change to sort by budget increasing. I don't know if this requires a new page site/findjob/sortbybudget, but I prefer to do this within site/findjob. I would appreciate any help or references I can read up to do this.

This is urls.py

from django.conf.urls.defaults import patterns, include, url

from project.preview.models import Task

info_task = {
    'queryset': Task.objects.all(),
    'template_name': 'template.html',
}

urlpatterns = patterns('',
    (r'^findtask/$', 'django.views.generic.list_detail.object_list', dict(info_task)),
)

This is: template.html

<div class="sortList">
**Sort by:**
<ul>
    <li class="sort"><a href=""/>Budget</a></li>
    <li class="sort"><a href=""/>Newly Added</li>
</ul>
</div>

<div class="taskListCon">
        {% for object in object_list %}
        <div class="taskCon">
          <div class="Title">
          {{ object.title_description }}
          </div>
          <div class="clientID">                    
          {{object.userid}}
          </div>
          <div class="Price">
          Budget:{{ object.max_budget }}
        </div>
<div>
{% endfor %}

Upvotes: 3

Views: 1943

Answers (3)

nopogo
nopogo

Reputation: 70

Another option is the use of django-filter. Just check out the example app:

https://github.com/alex/django-filter

Upvotes: 1

Mikael
Mikael

Reputation: 3236

Personally I would use something like jQuery tablesorter to solve this. This will save you a roundtrip to the server for each sort.

Docs: http://tablesorter.com/docs/

Upvotes: 2

jpic
jpic

Reputation: 33410

Rather than reinventing the wheel, the solution i propose is to enjoy a reusable app that does it right.

django-tables2 simplifies the task of turning sets of data into HTML tables. It has native support for pagination and sorting. It does for HTML tables what django.forms does for HTML forms. e.g.

Its features include:

  • Any iterable can be a data-source, but special support for Django querysets is included.
  • The builtin UI does not rely on JavaScript.
  • Support for automatic table generation based on a Django model.
  • Supports custom column functionality via subclassing.
  • Pagination.
  • Column based table sorting.
  • Template tag to enable trivial rendering to HTML.
  • Generic view mixin for use in Django 1.3.

Screenshot

Upvotes: 2

Related Questions