0

I have a cart model and I want in API which if the user the add same items two times in cart the cart will automatically increase the quantity of service. In my case, if I add the same item twice it creates another cart instead of updating the previous one. I search for it a lot but I don't get an answer. I tried a lot to do this. If somebody is capable of giving answer then please give an answer , please
Here is my code:-

views.py

class CartViewSet(viewsets.ModelViewSet):
    serializer_class = CartSerializer
    permission_classes = (IsAuthenticated,)
    def get_queryset(self):
        user = self.request.user
        if user.is_authenticated:
            if user is not None:
                if user.is_active and user.is_superuser or user.is_Customer:
                    return Cart.objects.all()
                raise PermissionDenied()
            raise PermissionDenied()
        raise PermissionDenied()
    filter_backends = [DjangoFilterBackend]
    filterset_fields = ['date_created', 'user']
    @action(detail=False)
    def count(self, request):
        queryset = self.filter_queryset(self.get_queryset())
        count = queryset.count()
        content = {'count': count}
        return Response(content)

serializers.py

class CartSerializer(serializers.ModelSerializer):
    class Meta:
        model = Cart
        fields = ['id','url', 'user', 'service', 'defects', 'date_created', 'quantity' , 'price', 'total']

models.py

class Cart(models.Model):
    user = models.ForeignKey('accounts.User', related_name="carts", null=True, on_delete=models.SET_NULL)
    quantity = models.IntegerField(default=1)
    service = models.ForeignKey('accounts.SubCategory',null=True,  on_delete=models.SET_NULL)
    defects = models.ForeignKey('Defects',null=True,  on_delete=models.SET_NULL)
 
    price = models.IntegerField(default=False)
    date_created = models.DateTimeField(auto_now_add=True)
    total = models.IntegerField(blank=True, null=True)    

    def __str__(self):
        return self.user.username

3
  • Can't see the code where you actually increase the quantity. Could you please add it? Commented Aug 14, 2020 at 7:51
  • bro, there is no code to increase the quantity Commented Aug 14, 2020 at 9:39
  • will please suggest me for the code of increase quantity Commented Aug 14, 2020 at 9:40

2 Answers 2

1

You have to override create method in you CartSerializer you can able to check and update if already created. I will mention some stuff tying this

Override Create method

class CartSerializer(serializers.ModelSerializer):
    class Meta:
        model = Cart
        fields = ['id','url', 'user', 'service', 'defects', 'date_created', 'quantity' , 'price', 'total']

    def create(self,validated_data):
        """ Create cart if not created """
        cart,created = Cart.objects.get_or_create(**validated_data)
        if not created:
           cart.quantity=cart.quantity+1
        # you have to write your own logic i give you just an hint 
        return cart

Here we override create method it's invoking whenever we do post a request on the cart URL at the time we can change flow of creating an object of the cart

Hope you understand if you have any query concern let me know

Sign up to request clarification or add additional context in comments.

3 Comments

bro that not work, If I add the same item twice in the cart it creates 2 carts and I want only one with quantity two
I told the way you have to follow I am not able to give you whole logic because I do not any which model foreigner you use within this stuff and any model so I have mentioned in the answer also you have to override create method in your serializer and way I told you it definitely work here don't copy exact code apply logic in create method and return cart object
bro, will you please tell me how to use that's all my code for Cart, please
0

I have discovered some best practices, below I will be showing a generalized way how to update API with function-based views which can be used with class bases views. *** Note you must have some id or unique field to identify the objects in the payload of JSON

Models.py 
 class Product(models.Model):
   actual_product_id=models.Autofield(primary_key=True,auto_created=True)
   price ....
   etc

Serializers.py

from .import Product
class Product_Serializers(models.ModelSerializer):
   class Meta:
     model=Product
     fields='__all__'

Raw Json format which will bw received by api 
{  "some_product_id":"4163",
   "price ": "41"
}
Urls.py

from django.conf.urls import url 

url(r'^/api/productview',views,productview),

Views.py 

@api_view(['PUT','GET','POST'])


def productview(request):
    json_response=JSONParser().parse(request)
        
        if "some_product_id" in json_response:
            doctor_requested_id=json_response['some_product_id']
     
            verified_object=Product.objects.filter(
            some_product_id=actual_product_id)

            verified_object.update(**json_response)
            return JsonResponse({'message':"product has been updated 
              succesfully"},status=status.HTTP_200_OK)
        else :
            return JsonResponse({'message':"product's id dosen't exist"})

Hope it can solve the issue .

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.