fix the order when getting next or prev post and at the post view

This commit is contained in:
2024-08-25 20:37:17 +02:00
parent f121239d31
commit 13d7969532
2 changed files with 19 additions and 6 deletions

View File

@@ -37,7 +37,7 @@ class PostManager(PublishedManager, models.Manager):
When(post_type="F", then="event_start__date"), When(post_type="F", then="event_start__date"),
) )
) )
return qs.order_by("-date") return qs.order_by("-date", "-id")
def date_sorted_list(self, public=True): def date_sorted_list(self, public=True):
return self.published(public) return self.published(public)
@@ -76,7 +76,7 @@ class ArticleManager(PublishedManager, models.Manager):
When(post_type="E", then="event_start__date"), When(post_type="E", then="event_start__date"),
) )
) )
return qs.order_by("-date") return qs.order_by("-date", "-id")
def date_sorted_list(self, public=True): def date_sorted_list(self, public=True):
return self.published(public) return self.published(public)

View File

@@ -4,6 +4,7 @@ from datetime import timedelta
from django.conf import settings from django.conf import settings
from django.contrib.auth.mixins import LoginRequiredMixin from django.contrib.auth.mixins import LoginRequiredMixin
from django.http import Http404, HttpResponse from django.http import Http404, HttpResponse
from django.db.models import Q
from django.shortcuts import render from django.shortcuts import render
from django.template.loader import render_to_string from django.template.loader import render_to_string
from django.views.generic.detail import DetailView from django.views.generic.detail import DetailView
@@ -147,9 +148,15 @@ class PostDetailView(DetailView):
posts = Post.objects.date_sorted_list(self.public_only).filter( posts = Post.objects.date_sorted_list(self.public_only).filter(
post_type=self.object.post_type post_type=self.object.post_type
) )
qs = posts.filter(date__lt=self.object.date) qs = posts.filter(
# Get posts which are in the future.
Q(date__lt=self.object.date)
# Get posts which have the same date but id is lower.
| (Q(date__lte=self.object.date) & Q(id__lt=self.object.id))
)
if not qs: if not qs:
qs = posts[:1] # If there are any prev posts, then take the latest one.
qs = posts
return qs.first().slug return qs.first().slug
@@ -162,9 +169,15 @@ class PostDetailView(DetailView):
.filter(post_type=self.object.post_type) .filter(post_type=self.object.post_type)
.reverse() .reverse()
) )
qs = posts.filter(date__gt=self.object.date) qs = posts.filter(
# Get posts which are in the past.
Q(date__gt=self.object.date)
# Get posts which have the same date but id is greater.
| (Q(date__gte=self.object.date) & Q(id__gt=self.object.id))
)
if not qs: if not qs:
qs = posts[:1] # If there are any next posts, then take the first one.
qs = posts
return qs.first().slug return qs.first().slug