'Reduce stock in the database with django

I created a stock for the coffee beans in the database, and want to decrease the stock whenever CoffePods are created indicating the decrease of the beans stock.

How to reduce the CoffeBeans stock in the database each time I create CoffePods which is received as a query parameter from the URL and what is the best practice in this case?

views.py

class PodsViewSet(viewsets.ModelViewSet):
    queryset = CoffePods.objects.all().order_by('id')
    serializer_class  = CoffePodsSerializer
    serializer_class  = CoffeBeansSerializer
    filter_backends   = [django_filters.rest_framework.DjangoFilterBackend]
    filterset_fields  = '__all__'

    def create(self, request, *args, **kwargs):
        print("Coffe Pod Created!")
        try:
            pods_pack_size = int(self.request.query_params.get('pack_size'))
            coffe_beans = CoffeBeans.objects.all()[0]
            
            if coffe_beans.capacity > 2.0 and coffe_beans.quantity > 4:
                
                if pods_pack_size == 1:
                    coffe_beans.capacity -= 0.5
                    coffe_beans.quantity -= 1
                    coffe_beans.save()

                elif pods_pack_size == 2:
                    coffe_beans.capacity -= 1.0
                    coffe_beans.quantity -= 2
                    coffe_beans.save()

                
                elif pods_pack_size == 3:
                    coffe_beans.capacity -= 1.5
                    coffe_beans.quantity -= 3
                    coffe_beans.save()

                elif pods_pack_size == 4:
                    coffe_beans.capacity -= 2.0
                    coffe_beans.quantity -= 4
                    coffe_beans.save()

        except Exception as e:
            raise e

        return Response(coffe_beans)

models.py

class CoffeBeans(models.Model):
    capacity  = models.FloatField(validators=[MinValueValidator(0.0)], default=100)
    quantity  = models.PositiveIntegerField(default=200)

    class Meta:
        verbose_name_plural = 'Coffe Beans'

    def __str__(self):
        return f"{self.capacity} KG - {self.quantity} Pack"


Solution 1:[1]

You could write a model method to do this

class CoffeBeans(models.Model):
    capacity  = models.FloatField(validators=[MinValueValidator(0.0)], default=100)
    quantity  = models.PositiveIntegerField(default=200)

    class Meta:
        verbose_name_plural = 'Coffe Beans'

    def __str__(self):
        return f"{self.capacity} KG - {self.quantity} Pack"

    def reduce_coffebean(self, pods_pack_size):
        self.capacity -= pods_pack_size/2
        self.quantity -= pods_pack_size
        self.save()

You can then just call coffebeans.reduce_coffebean(pods_pack_size) in your views.py

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Arun T