Files
tripwithbonus/backend/api/search/views.py

44 lines
1.9 KiB
Python

from rest_framework import generics
from typing import cast
from rest_framework.request import Request
from routes.models import Route
from .serializers import SearchRouteSerializer
from api.utils.pagination import StandardResultsSetPagination
from rest_framework.exceptions import ValidationError
from routes.constants.routeChoices import owner_type_choices
from django.utils import timezone
class SearchRouteListView(generics.ListAPIView):
serializer_class = SearchRouteSerializer
pagination_class = StandardResultsSetPagination
def get_queryset(self):
owner_type = self.kwargs.get('owner_type')
from_city = cast(Request, self.request).query_params.get('from')
to_city = cast(Request, self.request).query_params.get('to')
valid_types = [choice[0] for choice in owner_type_choices]
current_time = timezone.now()
if not owner_type or owner_type not in valid_types:
raise ValidationError("Invalid or missing owner_type. Must be either 'customer' or 'mover'")
# базовый фильтр по типу владельца и актуальности
queryset = Route.objects.filter(
owner_type=owner_type,
status="actual")
# фильтруем по городам если они указаны
if from_city:
queryset = queryset.filter(from_city__name__iexact=from_city)
if to_city:
queryset = queryset.filter(to_city__name__iexact=to_city)
# фильтруем по времени в зависимости от типа
if owner_type == 'mover':
queryset = queryset.filter(departure_DT__gt=current_time)
else: # customer
queryset = queryset.filter(arrival_DT__gt=current_time)
return queryset.order_by('-arrival_DT')