Breaking News

wings 1 track t4 django final code

 

models.py

 

 class Item(models.Model):
  id =models.AutoField(primary_key=True)
  name = models.CharField(max_length=250)
  category=models.CharField(max_length=250)
  price=modelsIntegerField()
  quantity=modelsIntegerField()
  barcode=models.IntegerField(unique=True)

 

 

admin.py 


from django.contrib import admin
from .models import Item


admin.site.register(Item) 



serilalizers

from models import Item


class ItemSerializer(serializers.ModelSerializer):
  class Meta:
    model=Item
    fields ='__all__'


url.py


from django.urls import include, path
from django.contrib import admin
from inventory.views import InventoryItemView, QueryItemsView,SortItemsView
urlpatterns =[
  path('admin/', admin.site.urls),
  path('inventory/items/', InventoryItemView.as_view(), name='inventory-items'),
  path('inventory/items/<int:pk>/', InventoryItemView.as_view(), name='inventory-detail'),
  path('items/sort/', SortItemsView.as_view(), name='sort-items'),
  path('items/quer/<str:category>/', QueryItemsView.as_view(), name='query-items'),
]


views.py


from rest_framework import viewsets
from rest_framework.views import APIView
from rest_framework.response import Response
from invetoryapp.seializers import ItemSerializer
from .models import item
from rest_framework import status



class SortItemsView(APIView):
  def get(self, request):
    items = Item.objects.all().order_by('-price')
    serializer = ItemSerializer(items, many=True)
    return Response(serializer.data)
class QueryItemsView(APIView):
  def get(self, request,category):
    items = Item.objects.filter(category=category)
    serializer = ItemSerializer(items, many=True)
    return Response(serializer.data)
class InventoryItemView(APIView):
  def get(self, request):
    items = item.objects.all()
    serializer = ItemSerializer(items, many=True)
    return Response(serializer.data)
  def post(self, request):
    serializer=ItemSerializer(data=request.data)
    if serializer.is_valid():
        barcode=serializer.validated_data['barcode']
        item_exists=Item.objects.filter(barcode=barcode).exists()
        if item_exists:
          return Response({'error':'Item already exists'}, status=status.HTTP_400_BAD_REQUEST)
        serializer.save()
        return Response(serializer.data, status=status.HTTP_201_CREATED)
    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
  def delete(self, request, pk):
    try:
        item =Item.objects.get(pk=pk)
    except Item.DoesNotExist:
      return Response(status=status.HTTP_404_NOT_FOUND)
      item.delete()
    return Response(status=status.HTTP_204_NO_CONTENT)
    return Response(status=status.HTTP_204_NO_CONTENT)

No comments