Reputation: 15
I am setting up a blog website and when I add blog posts, the oldest is on the top of the list. How do I reverse this so that the newest posts are on top of the page?
This is my pages/models.py I don't know if ordered_posts = Post.objects.order_by('created_date') is in the right place. I'm not sure where to put it. Any help would be appreciated. Thanks!
class Post(models.Model):
title = models.CharField(max_length=50)
created_date = models.DateTimeField(default=timezone.now)
published_date = models.DateTimeField(auto_now_add=True blank=True, null=True)
author = models.ForeignKey(
'auth.User',
on_delete=models.CASCADE,
)
body = models.TextField()
ordered_posts = Post.objects.order_by('-created_date')
def publish(self):
self.published_date = timezone.now()
self.save()
def __str__(self):
return self.title
Upvotes: 0
Views: 601
Reputation: 5742
You can define ordering
in your class Meta.
This is a tuple or list of strings and/or query expressions. Each string is a field name with an optional “-” prefix, which indicates descending order. Fields without a leading “-” will be ordered ascending.
class Post(models.Model):
title = models.CharField(max_length=50)
created_date = models.DateTimeField(default=timezone.now)
published_date = models.DateTimeField(auto_now_add=True blank=True, null=True)
author = models.ForeignKey(
'auth.User',
on_delete=models.CASCADE,
)
body = models.TextField()
def publish(self):
self.published_date = timezone.now()
self.save()
def __str__(self):
return self.title
class Meta:
ordering = ['created_date']
Upvotes: 2