phase7: add minimal read-only drf api with player search endpoints
This commit is contained in:
68
apps/api/views.py
Normal file
68
apps/api/views.py
Normal file
@ -0,0 +1,68 @@
|
||||
from rest_framework import generics
|
||||
from rest_framework.pagination import PageNumberPagination
|
||||
from rest_framework.throttling import AnonRateThrottle, UserRateThrottle
|
||||
|
||||
from apps.competitions.models import Competition, Season
|
||||
from apps.players.forms import PlayerSearchForm
|
||||
from apps.players.models import Player
|
||||
from apps.players.services.search import apply_sorting, base_player_queryset, filter_players
|
||||
from apps.teams.models import Team
|
||||
|
||||
from .permissions import ReadOnlyOrDeny
|
||||
from .serializers import (
|
||||
CompetitionSerializer,
|
||||
PlayerDetailSerializer,
|
||||
PlayerListSerializer,
|
||||
SeasonSerializer,
|
||||
TeamSerializer,
|
||||
)
|
||||
|
||||
|
||||
class ApiPagination(PageNumberPagination):
|
||||
page_size = 20
|
||||
page_size_query_param = "page_size"
|
||||
max_page_size = 100
|
||||
|
||||
|
||||
class ReadOnlyBaseAPIView:
|
||||
permission_classes = [ReadOnlyOrDeny]
|
||||
throttle_classes = [AnonRateThrottle, UserRateThrottle]
|
||||
|
||||
|
||||
class PlayerSearchApiView(ReadOnlyBaseAPIView, generics.ListAPIView):
|
||||
serializer_class = PlayerListSerializer
|
||||
pagination_class = ApiPagination
|
||||
|
||||
def get_queryset(self):
|
||||
form = PlayerSearchForm(self.request.query_params or None)
|
||||
queryset = base_player_queryset()
|
||||
if form.is_valid():
|
||||
queryset = filter_players(queryset, form.cleaned_data)
|
||||
queryset = apply_sorting(queryset, form.cleaned_data.get("sort", "name_asc"))
|
||||
else:
|
||||
queryset = queryset.order_by("full_name", "id")
|
||||
return queryset
|
||||
|
||||
|
||||
class PlayerDetailApiView(ReadOnlyBaseAPIView, generics.RetrieveAPIView):
|
||||
serializer_class = PlayerDetailSerializer
|
||||
queryset = Player.objects.select_related(
|
||||
"nationality",
|
||||
"nominal_position",
|
||||
"inferred_role",
|
||||
).prefetch_related("aliases")
|
||||
|
||||
|
||||
class CompetitionListApiView(ReadOnlyBaseAPIView, generics.ListAPIView):
|
||||
serializer_class = CompetitionSerializer
|
||||
queryset = Competition.objects.select_related("country").order_by("name")
|
||||
|
||||
|
||||
class TeamListApiView(ReadOnlyBaseAPIView, generics.ListAPIView):
|
||||
serializer_class = TeamSerializer
|
||||
queryset = Team.objects.select_related("country").order_by("name")
|
||||
|
||||
|
||||
class SeasonListApiView(ReadOnlyBaseAPIView, generics.ListAPIView):
|
||||
serializer_class = SeasonSerializer
|
||||
queryset = Season.objects.order_by("-start_date")
|
||||
Reference in New Issue
Block a user