Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: bugfix for top query #478

Merged
merged 2 commits into from
Dec 9, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 21 additions & 10 deletions apps/core/serializers/article.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import datetime
from enum import Enum

from django.utils import timezone
from django.utils.translation import gettext
from rest_framework import exceptions, serializers
from rest_framework.utils.serializer_helpers import ReturnDict
Expand Down Expand Up @@ -177,9 +179,14 @@ def filter_articles(obj, request):
return articles

elif from_view == "top":
top_articles = Article.objects.exclude(topped_at__isnull=True).order_by(
"-topped_at", "-pk"
current_date = datetime.datetime.combine(
timezone.now().date(), datetime.time.min, datetime.timezone.utc
)
# get the articles that are created_at within a week and order by hit_count
top_articles = Article.objects.filter(
created_at__gte=current_date - datetime.timedelta(days=7)
).order_by("-hit_count", "-pk")

if not top_articles.filter(id=obj.id).exists():
raise serializers.ValidationError(
gettext("This article is not in top articles.")
Expand Down Expand Up @@ -245,19 +252,23 @@ def get_side_articles(self, obj) -> dict:
else:
after = None
elif from_view == "top":
before = articles.filter(topped_at__lte=obj.topped_at).first()
after = articles.filter(topped_at__gte=obj.topped_at).last()
before = articles.filter(created_at__lte=obj.created_at).first()
after = articles.filter(created_at__gte=obj.created_at).last()
else:
before = articles.filter(created_at__lte=obj.created_at).first()
after = articles.filter(created_at__gte=obj.created_at).last()

return {
"before": SideArticleSerializer(before, context=self.context).data
if before
else None,
"after": SideArticleSerializer(after, context=self.context).data
if after
else None,
"before": (
SideArticleSerializer(before, context=self.context).data
if before
else None
),
"after": (
SideArticleSerializer(after, context=self.context).data
if after
else None
),
}

def get_side_articles_of_recent_article(self, obj, request):
Expand Down
Loading