ordering in listview of django
Asked Answered
W

1

6

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 ?

Winnipegosis answered 25/11, 2018 at 5:12 Comment(3)
Add date and make it auto_now_add to true. And you can skip it in html if you don't want it on the html. That I guess the simplest solution.Leeth
do i have to run makemigrations for that ? cause last time when i did this , i had to delete entire database .Winnipegosis
You don't need to delete the entire database. Just add date in your model and run makemigrations and migrate. You can also sort it by pk.Leeth
P
7

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
Peptize answered 25/11, 2018 at 5:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.