Search code examples
djangosortinglistviewdjango-generic-views

ordering in listview of django


i am in django 2 and facing some issues here. Let me give you my files first

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

problem is i want to order the elements of {{ snippet_form_model }} into reverse order but i didnt specified date in that model to order by. Is there any sort of different way to set the order ?


Solution

  • You can update the ordering like this:

    # 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