The Django Djitney: Sorting stops by stop_number (after Task 25)

The Django Djitney project Task 25 requires to insert a stop at Basuto station on the Monty line, between Cob and Anadolu station. After following instructions, I found that stops in Stop page, Lines page, and Home page was not sorted by stop_number. Here are some tips for fixing it.

  1. Specify ordering attribute of the StopsView class in views.py.
class StopsView(ListView):
  ...
  ordering = ['line', 'stop_number']

  1. Use built-in filter dictsort in templates lines.html and home.html.
{% for stop in line.stop_set.all|dictsort:"stop_number" %}

Hello!

Great work!

Another solution is to specify default ordering in model:

class Stop(models.Model):
  class Meta:
    unique_together = (('line', 'stop_number'))
    ordering = [ 'line', 'stop_number' ]

Together with unique key, specified by unique_together, this will work on database query level, which sometimes is faster then sorting result of the query on app level.

1 Like