Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(Django) Order by desc

Tags:

python

django

I can not order my News table. I guess i did everything right but django shows me error! Please check my code maybe something went wrong

class News(models.Model):
news_title = models.CharField(max_length=255)
news_text = models.TextField(max_length=1000)
news_logo = models.ImageField(upload_to='uimages')
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)

class Meta:
    verbose_name = 'News'
    verbose_name_plural = 'News'
    **News.objects.filter().order_by('-created_at')**
like image 634
Dustin Avatar asked Sep 20 '25 18:09

Dustin


1 Answers

There are some indentation problems in your code, or at least in the example you posted. The code snippet should be indented as follows:

class News(models.Model):
    news_title = models.CharField(max_length=255)
    news_text = models.TextField(max_length=1000)
    news_logo = models.ImageField(upload_to='uimages')
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        verbose_name = 'News'
        verbose_name_plural = 'News'

Specifically, the Meta class needs to be part of the News class.

In terms of changing the default ordering, as in some of the comments already pointed out, the correct way to do this is to use the ordering attribute inside the Meta class. If you always want to order by created_at in descending order, you'd need to define the classes as following:

class News(models.Model):
    news_title = models.CharField(max_length=255)
    news_text = models.TextField(max_length=1000)
    news_logo = models.ImageField(upload_to='uimages')
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        verbose_name = 'News'
        verbose_name_plural = 'News'
        ordering = ['-created_at']

You can find more information about model options in the Django documentation.

like image 188
m_____z Avatar answered Sep 22 '25 08:09

m_____z