Newer
Older
"""
Defines the views for the API
"""
from rest_framework import viewsets
from rest_framework.views import APIView
from rest_framework.response import Response
from .serializers import (
SmallSportListSerializer,
SportListSerializer,
CriterionListSerializer,
QuestionListSerializer,
)
from .models import Sport, Criterion, Question
class SportListView(viewsets.ModelViewSet): # pylint: disable=too-many-ancestors
"""
A View returning every Sport Object
"""
serializer_class = SportListSerializer
queryset = Sport.objects.all()
class CriterionListView(viewsets.ModelViewSet): # pylint: disable=too-many-ancestors
"""
A View returning every Criterion Object
"""
serializer_class = CriterionListSerializer
queryset = Criterion.objects.all()
class QuestionListView(viewsets.ModelViewSet): # pylint: disable=too-many-ancestors
"""
A View returning every Question Object
"""
serializer_class = QuestionListSerializer
queryset = Question.objects.all()
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
# Dev Notes:
# - If we want to include a View in the Router in urls.py, the View needs to be a Viewset
# - Those are mostly meant for Lists of Objects, so instead of get() and post(), list() and create() are used respectively
# https://stackoverflow.com/questions/30389248/how-can-i-register-a-single-view-not-a-viewset-on-my-router
class SmallSportListView(viewsets.ViewSet):
"""
View for the List of Sports on the Sport Homepage
TODO: More Documentation
"""
def list(self, request):
return Response({"test": 0})
# Dev Notes:
# - This is a singular APIView which isn't meant to expose complete lists
# - It cannot be written into the Router, as it isn't a Viewset, so it is written directly into the urls.py's urlspatterns like this:
# path(r"api/admin/single-small-sport-list", views.SmallSportListAPIView.as_view())
# - The API isn't in the list in /api/admin because of that, but needs to be called manually here:
# http://localhost:8000/api/admin/single-small-sport-list
class SmallSportListAPIView(APIView):
"""
View for the List of Sports on the Sport Homepage
TODO: More Documentation
"""
def get(self, request):
sports = Sport.objects.all()
criteria = Criterion.objects.all()
is_filled_tuples = []
for sport in sports.iterator():
filled_criteria_pks = []
# Get pks of Criteria which are connected to the sport
for criterion in sport.criteria_ratings.iterator():
filled_criteria_pks.append(criterion.pk)
is_filled = True
# Check every existing criterion whether it is in the generated list
for criterion in criteria.all():
if criterion.pk not in filled_criteria_pks:
# A criterion isn't filled out, so stop and set to false
is_filled = False
break
is_filled_tuples.append((sport, is_filled))
serializer = SmallSportListSerializer(is_filled_tuples)
return Response(serializer.data)