Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to order by date django post view

How can I order my posts from latest to oldest? I Use ordering = ['-date_posted'] for class based views. how can I do the exact thing for a function based view? this is my view function:

def blog_view(request):
    posts = Post.objects.all()
    paginator = Paginator(posts, 3)
    page = request.GET.get('page')
    posts = paginator.get_page(page)
    common_tags = Post.tags.most_common()[:]
    context = {
        'posts':posts,
        'common_tags':common_tags,
    }
    return render(request, 'posts/blog.html', context)
like image 273
Sam Avatar asked Nov 18 '25 09:11

Sam


1 Answers

you can do

posts = Post.objects.all().order_by('-date_posted')

or in your models add a meta class

 class Meta:
        ordering = ['-date_posted']
like image 179
bmons Avatar answered Nov 21 '25 06:11

bmons



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!