From 1ee215b0a5a1a214aa148757f741d7b6af9b9300 Mon Sep 17 00:00:00 2001
From: Samuel Gaist <samuel.gaist@idiap.ch>
Date: Wed, 22 Apr 2020 09:47:14 +0200
Subject: [PATCH] [common][api] Implement get_object in place of get_queryset
 for RetrieveUpdateDestroyContributionView

This view shall act on one object only and the check
should already be done there rather than in furhter
methods below.

It also follows the URL routes cleanup
---
 beat/web/common/api.py | 48 ++++++++++++------------------------------
 1 file changed, 14 insertions(+), 34 deletions(-)

diff --git a/beat/web/common/api.py b/beat/web/common/api.py
index 5fb277f21..2ce7b761a 100644
--- a/beat/web/common/api.py
+++ b/beat/web/common/api.py
@@ -235,46 +235,26 @@ class RetrieveUpdateDestroyContributionView(
 ):
     model = Contribution
 
-    def get_queryset(self):
-        version = self.kwargs.get("version", None)
-        author_name = self.kwargs.get("author_name")
-        object_name = self.kwargs.get("object_name")
+    def get_object(self):
+        version = self.kwargs["version"]
+        author_name = self.kwargs["author_name"]
+        object_name = self.kwargs["object_name"]
         user = self.request.user
-        if version is not None:
-            queryset = (
-                self.model.objects.for_user(user, True)
-                .filter(
-                    author__username__iexact=author_name,
-                    name__iexact=object_name,
-                    version__gte=version,
-                )
-                .order_by("version")
-            )
-        else:
-            queryset = (
-                self.model.objects.for_user(user, True)
-                .filter(author__username__iexact=author_name, name__iexact=object_name)
-                .order_by("-version")
+        try:
+            obj = self.model.objects.for_user(user, True).get(
+                author__username__iexact=author_name,
+                name__iexact=object_name,
+                version=version,
             )
-
-        return queryset
-
-    def get(self, request, *args, **kwargs):
-        db_objects = self.get_queryset()
-
-        if db_objects.count() == 0:
+        except self.model.DoesNotExist:
             raise drf_exceptions.NotFound()
+        return obj
 
-        db_object = db_objects[0]
-        version = int(self.kwargs.get("version", -1))
-
-        if version != -1 and db_object.version != version:
-            raise drf_exceptions.NotFound()
+    def get(self, request, *args, **kwargs):
+        db_object = self.get_object()
 
         # Process the query string
-        allow_sharing = hasattr(db_object, "author") and (
-            request.user == db_object.author
-        )
+        allow_sharing = request.user == db_object.author
 
         fields_to_return = self.get_serializer_fields(
             request, allow_sharing=allow_sharing
-- 
GitLab