From fcf0c392787ea45bf47f6ddfd9b9727d40f927e1 Mon Sep 17 00:00:00 2001
From: Calum Mackervoy <c.mackervoy@gmail.com>
Date: Thu, 21 May 2020 14:56:48 +0100
Subject: [PATCH] working TotalVotes Viewset

---
 djangoldp_polls/djangoldp_urls.py | 12 ++++++--
 djangoldp_polls/serializers.py    | 16 +++++++----
 djangoldp_polls/views.py          | 48 +++++++++++++++++++------------
 3 files changed, 49 insertions(+), 27 deletions(-)

diff --git a/djangoldp_polls/djangoldp_urls.py b/djangoldp_polls/djangoldp_urls.py
index 9ed6b63..583fa58 100644
--- a/djangoldp_polls/djangoldp_urls.py
+++ b/djangoldp_polls/djangoldp_urls.py
@@ -18,9 +18,15 @@ Including another URLconf
 from django.conf.urls import url,include
 from django.contrib import admin
 from .views import TotalVotes
-from djangoldp_poll.models import PollOption
+from djangoldp.models import Model
+from djangoldp_polls.models import PollOption
 
 urlpatterns = [
-    url(r'^test/$', Testing.as_view()),
-
+    url(r'^polls/total_votes/(?P<pk>[0-9]+)/', TotalVotes.urls(model_prefix='total-votes',
+                                                                model=PollOption,
+                                                                permission_classes=Model.get_meta(PollOption,
+                                                                                                  'permission_classes',
+                                                                                                  []),
+                                                                fields=Model.get_meta(PollOption, 'serializer_fields',[]),
+                                                                nested_fields=Model.get_meta(PollOption, 'nested_fields', []))),
 ]
\ No newline at end of file
diff --git a/djangoldp_polls/serializers.py b/djangoldp_polls/serializers.py
index 39bc2ec..299a9cf 100644
--- a/djangoldp_polls/serializers.py
+++ b/djangoldp_polls/serializers.py
@@ -1,9 +1,15 @@
+from rest_framework import serializers
 from djangoldp.serializers import LDPSerializer
-from djangoldp_polls.models import Poll,PollOption
+from djangoldp_polls.models import PollOption
+
 
 class PollOptionSerializer(LDPSerializer):
-	total_votes = serializers.SerializerMethodField()
+    total_votes = serializers.SerializerMethodField()
+
+    class Meta:
+        model = PollOption
+        fields = ['urlid', 'total_votes']
 
-        def get_total_votes(self, obj):
-            votes_queryset = self.context.get("votes_queryset")
-            return votes.filter(chosenOption=choice).count()
\ No newline at end of file
+    def get_total_votes(self, obj):
+        votes_queryset = self.context.get("votes_queryset")
+        return votes_queryset.filter(chosenOption=obj).count()
diff --git a/djangoldp_polls/views.py b/djangoldp_polls/views.py
index 44ec1fa..d6cbe8a 100644
--- a/djangoldp_polls/views.py
+++ b/djangoldp_polls/views.py
@@ -1,36 +1,46 @@
+from django.http import Http404
+
 from djangoldp.views import LDPViewSet
 from datetime import datetime
-from .models import Poll,Vote
+from rest_framework import status
 from rest_framework.views import APIView
 from rest_framework.response import Response
 
+from .models import Poll,Vote
+from .serializers import PollOptionSerializer
 
 
 class FuturePollViewset(LDPViewSet):
     model = Poll
+
     def get_queryset(self):
         return super().get_queryset().filter(enddate__gte=datetime.now())
 
-class TotalVotes(LDPViewSet) : 
-    list_actions = {'get': 'list'}
-    detail_actions = {}
 
-    # view to GET the total counts of votes selecting a particular option
-    def list(self, request, pk, *args, **kwargs):
-        try:
-            poll = Poll.objects.get(pk=pk)
-        except Poll.DoesNotExist:
-            return Response(data={'error': 'could not get a Poll with this ID!'}, status=status.HTTP_404_NOT_FOUND)
+class TotalVotes(LDPViewSet):
+    '''view to GET the total counts of votes selecting a particular option'''
 
-        votes = poll.votes.all()
-        kwargs['context'] = self.get_serializer_context()
-        kwargs['context'].update({'votes_queryset': votes})
-        choices = poll.userVote.all()
-        serializer = PollOptionSerializer(choices, many=True)
+    def _get_poll_or_404(self):
+        pk = self.kwargs['pk']
 
-        return Response(serializer.data, status=status.HTTP_200_OK)
+        try:
+            return Poll.objects.get(pk=pk)
+        except Poll.DoesNotExist:
+            raise Http404('could not get a Poll with this ID!')
 
+    def get_serializer_context(self):
+        poll = self._get_poll_or_404()
 
-class Testing(APIView):
-    def get(self, request):
-        return Response("Hello world") 
\ No newline at end of file
+        votes = poll.votes.all()
+        context = super().get_serializer_context()
+        context.update({'votes_queryset': votes})
+        return context
+
+    def get_queryset(self, *args, **kwargs):
+        poll = self._get_poll_or_404()
+        return poll.pollOptions.all()
+
+    def get_serializer_class(self):
+        # NOTE: this is required because currently DjangoLDP overrides the serializer_class during __init__
+        # https://git.startinblox.com/djangoldp-packages/djangoldp/issues/241
+        return PollOptionSerializer
-- 
GitLab