Django只按日期排序ListView

zc0qhyus  于 2023-03-09  发布在  Go
关注(0)|答案(1)|浏览(94)

我正在处理一些从开发者那里继承的Django代码,需要做一个非常简单的修改。在代码中,有一个通过Django ListView显示的作业列表。我的问题真的很简单。当我进入页面时,我看到作业按照日期排序,最早的排在最前面。我想按照相反的顺序排序作业。我不需要任何过滤,在URL中传递参数,等等。以下是文件的相关部分:

#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')
]

如前所述,这会导致作业按“创建”字段排序显示。较早创建的作业会首先显示。要使较晚创建的作业首先显示,最快的方法是什么?

tyg4sfes

tyg4sfes1#

第一条路

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']

第二条路

views.py

from .models import Job
class JobListView(ListView):
    template_name="jobs/list.html"
    queryset = Job.objects.order_by('-created')
    paginate_by = 10

相关问题