在Django的列表视图中排序

时间:2018-11-25 05:12:09

标签: django sorting listview django-generic-views

我在Django 2中,在这里遇到了一些问题。我先给你我的文件

views.py

class home_view(ListView):
    model = home_blog_model
    template_name = "home.html"
    context_object_name = "posts"
    paginate_by = 6
    ordering = ['-date']


    def get_context_data(self , **kwargs):
        context = super(home_view , self).get_context_data(**kwargs)
        context.update({"snippets":snippet_form_model.objects.all()})
        return context

models.py

class snippet_form_model(models.Model):
    title = models.CharField(max_length=500)
    language = models.CharField(max_length=50)
    code = models.TextField()
    describe = models.TextField()



    class Meta:
        ordering = ['-created']


    def __str__(self):
        return self.title

问题是我想将{{snippet_form_model}}的元素按相反的顺序排序,但是我没有在该模型中指定要排序的日期。有什么不同的方式设置订单吗?

1 个答案:

答案 0 :(得分:1)

您可以像这样更新订单:

# Please read PEP-8 Docs for naming
# Class name should be Pascal Case

class snippet_form_model(models.Model):
    title = models.CharField(max_length=500)
    language = models.CharField(max_length=50)
    code = models.TextField()
    describe = models.TextField()

    class Meta:
        ordering = ['-id']  # as you don't have created field. Reverse by ID will also show give you snippet_form_model in reverse order

    def __str__(self):
        return self.title