From 068d13261b050893f696e17cd28131c983e5c095 Mon Sep 17 00:00:00 2001 From: Dirk Jahnke Date: Mon, 30 May 2022 11:41:48 +0200 Subject: [PATCH] Fixed filters and GTIN retrieval. --- api/urls.py | 2 +- api/views.py | 30 +++++++++++++++++++++++++++--- 2 files changed, 28 insertions(+), 4 deletions(-) diff --git a/api/urls.py b/api/urls.py index 7a0f0fb..b004f97 100644 --- a/api/urls.py +++ b/api/urls.py @@ -11,5 +11,5 @@ router.register(r'products', GtinProductViewSet) urlpatterns = [ path('', include(router.urls)), - path('api-auth/', include('rest_framework.urls', namespace='rest_framework')) + path('auth/', include('rest_framework.urls', namespace='rest_framework')) ] \ No newline at end of file diff --git a/api/views.py b/api/views.py index 2c902c8..dd47a07 100644 --- a/api/views.py +++ b/api/views.py @@ -1,6 +1,9 @@ -from django.shortcuts import render -from rest_framework import viewsets +from rest_framework import viewsets, status from rest_framework import permissions +from rest_framework.decorators import action +from rest_framework.response import Response + +import asset.gtin_service from api.serializers import ContainerSerializer, ContainerTypeSerializer, AssetSerializer, GtinProductSerializer from container.models import Container, ContainerType from asset.models import Asset, GtinProduct @@ -36,7 +39,6 @@ class AssetViewSet(viewsets.ModelViewSet): filterset_fields = ['named_id', 'quantity'] - class GtinProductViewSet(viewsets.ModelViewSet): """ API endpoint that allows containers to be viewed or edited. @@ -46,3 +48,25 @@ class GtinProductViewSet(viewsets.ModelViewSet): permission_classes = [permissions.IsAuthenticated] filterset_fields = ['gtin'] + def retrieve(self, request, pk=None): + if pk: + item = GtinProduct.objects.get(id=pk) + serializer = GtinProductSerializer(item) + return Response({"status": "success", "data": serializer.data}, status=status.HTTP_200_OK) + + items = GtinProduct.objects.all() + serializer = GtinProductSerializer(items, many=True) + return Response({"status": "success", "data": serializer.data}, status=status.HTTP_200_OK) + + @action(detail=True, methods=['GET']) + def by_gtin(self, request, gtin=None): + if gtin: + item = asset.gtin_service.get_by_gtin(gtin=gtin) + if item: + serializer = GtinProductSerializer(item) + return Response({"status": "success", "data": serializer.data}, status=status.HTTP_200_OK) + return Response( + {"status": "failed", "reason": "Could not find a product for given GTIN", "gtin": gtin}, + status=status.HTTP_404_NOT_FOUND) + return Response({"status": "failed", "reason": "No GTIN given, please provide a valid GTIN"}, + status=status.HTTP_400_BAD_REQUEST)