Two models : Post and Author
This view displays the last Post for each Author (author is a ForeignKey)
I want to have these posts in a descending order, but it does not work.
The template keeps displaying these in a ascending way.
I try this following:
views.py
class LastestListView(ListView):
context_object_name = 'posts'
model = models.Post
ordering = ['-date']
paginate_by = 10
def get_queryset(self):
return self.model.objects.filter(pk__in=
Post.objects.values('author__id').annotate(
max_id=Max('id')).values('max_id'))
or:
class LastestListView(ListView):
context_object_name = 'posts'
model = models.Post
paginate_by = 10
def get_queryset(self):
return self.model.objects.filter(pk__in=
Post.objects.order_by('-date').values('author__id').annotate(
max_id=Max('id')).values('max_id'))
Solution
The ordering has to be set in the beginning of the Queryset:
class LastestListView(ListView):
context_object_name = 'posts'
model = models.Post
paginate_by = 10
def get_queryset(self):
return self.model.objects.order_by('-date').filter(pk__in=
Post.objects.values('author__id').annotate(
max_id=Max('id')).values('max_id'))