Django just sort ListView by date

Question:

I’m dealing with some Django code I inherited from a dev and need to make a very simple change. In the code, there is a list of jobs displayed through a Django ListView. My problem is really simple. When I go to the page, I see the jobs sorted by date with earliest one first. I want to sort the jobs in the opposite order. I don’t need any filtering, passing parameters in the URL, etc for now. Here are the relevant parts of the files:

#models.py
from django.db import models
class Job(models.Model):
    created = models.DateTimeField(auto_now_add=True)
    position =  models.ManyToManyField(Position)
    title = models.CharField(max_length=100)

#views.py
from .models import Job
class JobListView(ListView):
    template_name="jobs/list.html"
    model = Job
    paginate_by = 10

#list.html
{% for job in object_list %}
    <li class="display-list-item">
        <h4><strong><a href="{% url 'job_detail' pk=job.pk %}">{{job.title}}</a></strong></h4>
        <ul class="list-inline job-info-list">                                                    
            <span>{{job.created | timesince}} ago</span>
        </ul>               
    </li>
{% endfor %}


#urls.py
urlpatterns = [
url('^$', views.JobListView.as_view(), name='job_list')
]

As mentioned, this causes the jobs to be displayed sorted by ‘created’ field. The ones created earlier are displayed first. What is the quickest way to make the ones created later display first?

Asked By: Rohit Pandey

||

Answers:

first way

models.py

from django.db import models
class Job(models.Model):
    created = models.DateTimeField(auto_now_add=True)
    position =  models.ManyToManyField(Position)
    title = models.CharField(max_length=100)

    class Meta:
       ordering = ['-created']

second way

views.py

from .models import Job
class JobListView(ListView):
    template_name="jobs/list.html"
    queryset = Job.objects.order_by('-created')
    paginate_by = 10
Answered By: Serjik
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.