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 ?

Ilya Berdichevsky
  • 1,249
  • 10
  • 24
Nitin Khandagale
  • 413
  • 5
  • 14
  • 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. – Bidhan Majhi Nov 25 '18 at 05:37
  • do i have to run makemigrations for that ? cause last time when i did this , i had to delete entire database . – Nitin Khandagale Nov 25 '18 at 05:46
  • 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. – Bidhan Majhi Nov 25 '18 at 05:49

1 Answers1

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
ruddra
  • 50,746
  • 7
  • 78
  • 101