Home > Software engineering >  How to store a computed value in a Django model
How to store a computed value in a Django model

Time:09-24

How to store the calculation of quantity * unit_price in the total model field?

class Orderdetails(models.Model):
    product = models.CharField(max_length=100,default='')
    quantity = models.IntegerField()
    unit_price = models.IntegerField()
    total= ()

CodePudding user response:

You can create a total method in your model and use it in your view (or wherever you want). Your model will look like this:

class OrderDetails(models.Model):
    product = models.CharField(max_length=100,default='')
    quantity = models.IntegerField()
    unit_price = models.IntegerField()
    
    def total(self):
        return self.quantity * self.unit_price

Then you can use it like OrderDetailsObject.total().

CodePudding user response:

For calculations, you may perform it in you your view.py, for example:

def my_function(request):
    if request.POST:
        ......
        ......
        my_product = OrderDetails(product=my_product, quantity=my_quantity, unit_price=my_unit_price, total=my_quantity * my_unit_price)
        my_product.save()

Alternatively, you may perform it as well while saving your model as follows:

class OrderDetails(Model.models):
    product = models.CharField(max_length=100,default='')
    quantity = models.IntegerField()
    unit_price = models.IntegerField()
    total= models.CharField(max_length=30)

    def get_total(self):
        result = self.quantity * self.unit_price
        return result

    def save(self, *args, **kwargs):
        self.total = self.get_total()
        super(OrderDetails, self).save(*args, **kwargs)

For serializer, you may perform the following:

from rest_framework import serializers
from .model import OrderDetails

class OrderDetailsSerializer(serializers.ModelSerializer):
    class Meta:
        model = OrderDetails
        fields = "__all__"
    def create(self, validated_data):
        order = OrderDetails(**validated_data)
        order.total = order.quantity * order.unit_price
        order.save()
        return order

and this is how to use the OrderDetailsSerializer in your view.py:

from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
from .model import OrderDetails

@api_view(['POST', 'GET'])
def order_details(request, format=None):
    if request.method == 'GET':
        orders = OrderDetails.objects.all()
        serializer = OrderDetailsSerializer(orders, many=True)
        return Response(serializer.data)
    
    elif request.method == 'POST':
        serializer = OrderDetailsSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response("success", status=status.HTTP_201_CREATED)
        
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
  • Related