Fixed filters and GTIN retrieval.

This commit is contained in:
Dirk Jahnke 2022-05-30 11:41:48 +02:00
parent 9247c27278
commit 068d13261b
2 changed files with 28 additions and 4 deletions

View File

@ -11,5 +11,5 @@ router.register(r'products', GtinProductViewSet)
urlpatterns = [ urlpatterns = [
path('', include(router.urls)), path('', include(router.urls)),
path('api-auth/', include('rest_framework.urls', namespace='rest_framework')) path('auth/', include('rest_framework.urls', namespace='rest_framework'))
] ]

View File

@ -1,6 +1,9 @@
from django.shortcuts import render from rest_framework import viewsets, status
from rest_framework import viewsets
from rest_framework import permissions 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 api.serializers import ContainerSerializer, ContainerTypeSerializer, AssetSerializer, GtinProductSerializer
from container.models import Container, ContainerType from container.models import Container, ContainerType
from asset.models import Asset, GtinProduct from asset.models import Asset, GtinProduct
@ -36,7 +39,6 @@ class AssetViewSet(viewsets.ModelViewSet):
filterset_fields = ['named_id', 'quantity'] filterset_fields = ['named_id', 'quantity']
class GtinProductViewSet(viewsets.ModelViewSet): class GtinProductViewSet(viewsets.ModelViewSet):
""" """
API endpoint that allows containers to be viewed or edited. API endpoint that allows containers to be viewed or edited.
@ -46,3 +48,25 @@ class GtinProductViewSet(viewsets.ModelViewSet):
permission_classes = [permissions.IsAuthenticated] permission_classes = [permissions.IsAuthenticated]
filterset_fields = ['gtin'] 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)