Django rest framework creating Orders and order items

1.1k Views Asked by At

I want to create a Order and order items. For this i am simply creating new model object in views.py using CreateApiView but i am receiving error that "Serializer_class" should be included but i don't need serializer for this.

//views.py

class CreateOrder(CreateAPIView):
        def Post(self,request):
            header_token = request.META.get('HTTP_AUTHORIZATION', None)
            print(header_token)
            access_token = header_token.split(' ')[1]
            status,user  = validate_token(access_token)
            cart=Cart.objects.get(user=user)
            print(cart)
            if cart:
                total=cart.total
                userprofile=UserProfile.objects.get(user=user)
                order,created=Order.objects.get_or_create(billing_profile=userprofile,total=total)
    
            cart_items=CartItem.objects.get(cart=cart)
            print(cart_items)
            for item in cart_items:
                itemid=item.item_id
                qty=item.quantity
                item_instance = Items.objects.get(item_id=item)
                order_item,created = OrderItems.objects.get_or_create(order=order, product=item_instance,quantity=qty)
                order.save()
                order_item.save()
                if created:
                    item.delete()
            return Response (status=rt_status.HTTP_200_OK)
        

I want to understand how to achieve this with or without serializer

1

There are 1 best solutions below

0
On

You are overriding the incorrect post method. If you look at the source code of CreateAPIView you will see the method named as shown below.

class CreateAPIView(mixins.CreateModelMixin, GenericAPIView):
    """
    Concrete view for creating a model instance.
    """
    def post(self, request, *args, **kwargs):
        return self.create(request, *args, **kwargs)

NOTE: The method is all lower case.

This method calls self.create which is derived from the CreateModelMixin and this method needs a serializer.

If you need something light weight where a serializer is not needed I would suggest using APIView.

from rest_framework.views import APIView

class CreateOrder(APIView):
    def post(self, request):
        ....