Django | Set the defulat ordering rule for queries in the models

Though we can specify order explicitly in queries like below


it is repetitive and most of the times we will want to order by a particular field.

We can specify the order in the models like this

class Post(models.Model):
    title = models.CharField(max_length=140)
    content = models.TextField()
    published = models.DateTimeField()

    def __unicode__(self):
        return self.title

    class Meta:
        ordering = ['published']

Leave a Reply

Your email address will not be published. Required fields are marked *