Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django just sort ListView by date

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?

like image 956
Rohit Pandey Avatar asked Nov 06 '16 03:11

Rohit Pandey


1 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
like image 175
Serjik Avatar answered Nov 20 '22 21:11

Serjik