简体   繁体   中英

How to update data in django rest framework

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM