ft_transcendence/tournament/serializers.py

38 lines
1.4 KiB
Python
Raw Normal View History

from rest_framework import serializers
from .models import TournamentModel
2023-12-26 12:24:23 -05:00
from games.serializers import GameSerializer
class TournamentSerializer(serializers.ModelSerializer):
levels = serializers.SerializerMethodField(read_only=True, required=False)
level = serializers.ReadOnlyField()
started = serializers.ReadOnlyField()
finished = serializers.ReadOnlyField()
2023-12-20 16:49:48 -05:00
name = serializers.CharField(default="")
class Meta:
model = TournamentModel
fields = ["name", "nb_players", "nb_players_by_game", "level", "started", "finished", "levels", "id"]
2023-12-26 12:24:23 -05:00
def get_levels(self, instance: TournamentModel):
levels: [[int]] = []
for i in range(instance.level):
2023-12-26 12:24:23 -05:00
games_id: [int] = instance.get_games_id_by_level(i)
if (games_id == []):
break
2023-12-26 12:24:23 -05:00
levels.append(games_id)
return levels
2023-12-20 16:49:48 -05:00
def validate_nb_players(self, value: int):
if (value < 2):
raise serializers.ValidationError("The numbers of players must be greather than 2.")
return value
def validate_nb_players_by_game(self, value: int):
if (value < 2):
raise serializers.ValidationError("The numbers of players by game must be greather than 2.")
nb_players: str = self.initial_data.get("nb_players")
if (nb_players is not None and nb_players.isnumeric()):
nb_players: int = int(nb_players)
if (value > nb_players):
raise serializers.ValidationError("The numbers of players by game must be smaller than the numbers of players.")
return value