59 lines
2.1 KiB
Python
59 lines
2.1 KiB
Python
from rest_framework import viewsets
|
|
from rest_framework.response import Response
|
|
from rest_framework import permissions, status
|
|
from rest_framework.authentication import SessionAuthentication
|
|
|
|
from django.http import HttpRequest
|
|
from django.contrib.auth import login
|
|
from django.db.models import QuerySet
|
|
|
|
from matchmaking.models import in_matchmaking
|
|
from .models import TournamentModel
|
|
from .serializers import TournamentSerializer
|
|
|
|
# Create your views here.
|
|
class TournamentViewSet(viewsets.ModelViewSet):
|
|
|
|
queryset = TournamentModel.objects.all
|
|
serializer_class = TournamentSerializer
|
|
permission_classes = (permissions.IsAuthenticated,)
|
|
authentication_classes = (SessionAuthentication,)
|
|
|
|
def perform_create(self, request: HttpRequest):
|
|
|
|
data: dict = request.data
|
|
|
|
nb_players_by_game = data.get("nb_players_by_game")
|
|
if (nb_players_by_game is None):
|
|
return Response("nb_player_by_game is required.", status=status.HTTP_400_BAD_REQUEST)
|
|
|
|
nb_players = data.get("nb_players")
|
|
if (nb_players is None):
|
|
return Response("nb_players is required.", status=status.HTTP_400_BAD_REQUEST)
|
|
|
|
tournament_id: int = TournamentModel().create(nb_players=nb_players, nb_players_by_game=nb_players_by_game)
|
|
|
|
return Response({"tournament_id": tournament_id}, status=status.HTTP_201_CREATED)
|
|
|
|
def list(self, request: HttpRequest, state: str = ""):
|
|
query: QuerySet
|
|
match state:
|
|
case "started":
|
|
query = TournamentModel.objects.filter(started=True, finished=False)
|
|
case "finished":
|
|
query = TournamentModel.objects.filter(finished=True)
|
|
case "currently":
|
|
query = TournamentModel.objects.filter(started=False, finished=False)
|
|
case _:
|
|
query = TournamentModel.objects.all()
|
|
serializer = TournamentSerializer(query, many=True)
|
|
return Response(serializer.data)
|
|
|
|
def retrieve(self, request: HttpRequest, pk):
|
|
|
|
if (not TournamentModel.objects.filter(pk=pk).exists()):
|
|
return Response({"detail": "Tournament not found."}, status=status.HTTP_404_NOT_FOUND)
|
|
|
|
tournament = TournamentModel.objects.get(pk=pk)
|
|
|
|
return Response(self.serializer_class(tournament).data, status=status.HTTP_200_OK) |