Home > database >  Calculate the total amount of the cart in django rest framework
Calculate the total amount of the cart in django rest framework

Time:10-09

I'm new in django,I need calculate cart summa and I have these models:

class Customer(Base):
    name = models.CharField(max_length=100)
    phone_number = models.CharField(max_length=100, blank=True, null=True)
    comments = models.CharField(max_length=255, blank=True, null=True)

class Cart(Base):
    user = models.ForeignKey(Customer, on_delete=models.CASCADE, related_name="cart")
    cart_number = models.CharField(max_length=500, default=increment_cart_number, null=True, blank=True)
    total_summa = models.FloatField()
    is_saved = models.BooleanField(default=False)

class Item(Base):
    cart = models.ForeignKey(Cart, on_delete=models.CASCADE, related_name='items')
    product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='product')
    product_price = models.FloatField()
    quantity = models.IntegerField(default=1)

I used generics view, Can i calculate cart summa like this

Bread 3x6000 = 18000 Milk 2x500 = 10000

Total_Summa = 28000

serializers.py

class CartCreateSerializer(serializers.ModelSerializer): 
  class Meta: 
    model = Cart 
    fields = [ 'id', 'user', 'cart_number', 'create_date', 'total_summa', 'time', 'is_saved', ]

Could you help me please?

CodePudding user response:

You can try the following using Sum and F expression

from django.db.models import F, Sum
cart.total_summa = Item.objects.filter(cart=cart).annotate(per_item_price=F('product_price')*F('quantity')).annotate(total_summa=Sum('per_item_price'))

Inside serializers you can use the following way

class CartCreateSerializer(serializers.ModelSerializer): 
    total_summa = serializers.SerializerMethodField("get_total_summa", read_only=True)
    class Meta: 
        model = Cart 
        fields = [ 'id', 'user', 'cart_number', 'create_date', 'total_summa', 'time', 'is_saved']
    
    def get_total_summa(self, obj):
        return obj.items.annotate(per_item_price=F('product_price')*F('quantity')).annotate(total_summa=Sum('per_item_price')).values('total_summa')
  • Related