45 lines
1.9 KiB
Python
45 lines
1.9 KiB
Python
from rest_framework import serializers
|
|
|
|
from django.db.models.query import QuerySet
|
|
|
|
from django.contrib.auth.models import User
|
|
|
|
from .models import TournamentModel
|
|
|
|
from profiles.models import ProfileModel
|
|
from profiles.serializers.ProfileSerializer import ProfileSerializer
|
|
from games.serializers import GameSerializer
|
|
|
|
class TournamentSerializer(serializers.ModelSerializer):
|
|
|
|
state = serializers.SerializerMethodField(read_only=True, required=False)
|
|
participants = serializers.SerializerMethodField(read_only=True, required=False)
|
|
round = serializers.ReadOnlyField()
|
|
started = serializers.ReadOnlyField()
|
|
finished = serializers.ReadOnlyField()
|
|
name = serializers.CharField(default="")
|
|
|
|
class Meta:
|
|
model = TournamentModel
|
|
fields = ["name", "nb_participants", "round", "started", "finished", "id", "state", "participants"]
|
|
|
|
def get_participants(self, instance: TournamentModel):
|
|
return ProfileSerializer(instance.get_participants(), many=True).data
|
|
|
|
def get_state(self, instance: TournamentModel):
|
|
return ["waiting", "started", "finished"][instance.started + instance.finished]
|
|
|
|
def validate_nb_participants(self, value: int):
|
|
if (value < 2):
|
|
raise serializers.ValidationError("The numbers of participants must be greather than 2.")
|
|
return value
|
|
|
|
def validate_nb_participants_by_game(self, value: int):
|
|
if (value < 2):
|
|
raise serializers.ValidationError("The numbers of participants by game must be greather than 2.")
|
|
nb_participants: str = self.initial_data.get("nb_participants")
|
|
if (nb_participants is not None and nb_participants.isnumeric()):
|
|
nb_participants: int = int(nb_participants)
|
|
if (value > nb_participants):
|
|
raise serializers.ValidationError("The numbers of participants by game must be smaller than the numbers of participants.")
|
|
return value |