Skip to content

Commit

Permalink
Merge pull request #493 from bounswe/fix/BE-search-with-tags
Browse files Browse the repository at this point in the history
Fix/BE search with tags
  • Loading branch information
oguzpancuk authored Dec 15, 2024
2 parents aa2b4b2 + 3353d09 commit 50a18d3
Showing 1 changed file with 45 additions and 1 deletion.
46 changes: 45 additions & 1 deletion backend/marketfeed/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
import yfinance as yf
from concurrent.futures import ThreadPoolExecutor
from django.db.models import Q
from drf_spectacular.utils import extend_schema, OpenApiParameter
from drf_spectacular.utils import extend_schema, OpenApiParameter, OpenApiTypes
from rest_framework.pagination import PageNumberPagination


Expand Down Expand Up @@ -455,6 +455,50 @@ def posts_by_tag(self, request, tag_id=None):
serializer = PostSerializer(queryset, many=True)
return Response(serializer.data)

@extend_schema(
parameters=[
OpenApiParameter(
name='tags',
type=OpenApiTypes.STR,
location=OpenApiParameter.PATH,
description='Comma-separated list of tag IDs (e.g., 1,2,3)',
required=True,
),
OpenApiParameter(
name='type',
type=OpenApiTypes.STR,
location=OpenApiParameter.QUERY,
description='Type of filter: "and" (all tags) or "or" (at least one tag)',
required=False,
)
]
)
@action(detail=False, methods=['get'], url_path='posts-by-tags/(?P<tags>[^/.]+)')
def posts_by_tags(self, request, tags=None):
if not tags:
return Response({'detail': 'No tags provided.'}, status=status.HTTP_400_BAD_REQUEST)

try:
tag_ids = [int(tag_id.strip()) for tag_id in tags.split(',') if tag_id.strip().isdigit()]
except ValueError:
return Response({'detail': 'Invalid tag IDs provided.'}, status=status.HTTP_400_BAD_REQUEST)

tags = Tag.objects.filter(id__in=tag_ids)
if not tags.exists():
return Response({'detail': 'No posts found for the specified tags.'}, status=status.HTTP_404_NOT_FOUND)

filter_type = request.query_params.get('type', 'or').lower()

if filter_type == 'and':
# Posts that have all the specified tags
for tag in tags:
posts = Post.objects.filter(tags=tag) if 'posts' not in locals() else posts.filter(tags=tag)
else: # Default to "or" behavior
# Posts that have at least one of the specified tags
posts = Post.objects.filter(tags__in=tags).distinct()

serializer = self.get_serializer(posts, many=True)
return Response(serializer.data, status=status.HTTP_200_OK)

class CommentViewSet(viewsets.ModelViewSet):
queryset = Comment.objects.all()
Expand Down

0 comments on commit 50a18d3

Please sign in to comment.