Server script calculation

I want to create a sever script formula , that multiplies number of items*rate to give the total amount , but it does not work please help

import frappe
from frappe.model.document import Document

class CashRequisition(Document):
    def validate(self):
        # Trigger calculation on validation before saving the document
        self.calculate_totals()

    def calculate_totals(self):
        total_quantity = 0
        total_amount = 0

        # Loop through each row in the child table "Cash Requisition Item"
        for item in self.items:
            # Calculate amount for each row
            if item.number_of_item and item.rate:
                item.amount = item.number_of_item * item.rate
            else:
                item.amount = 0  # Handle cases where values might be missing

            # Add to the total amount and total quantity
            total_quantity += item.number_of_item or 0
            total_amount += item.amount

        # Set the total_quantity and total_amount fields using self.set to track changes
        self.set('total_quantity', total_quantity)
        self.set('total_amount', total_amount)

Are you facing issues while setting up values to the field or in calculations?

i have set the fields , but still the problem persisits

If you want to calculate values before save, try on_update of before_save controller events. Also try to print the values and see if they are actually part of the final doctype

You can try as @Varun suggested, and it also sets the value in the validate method. Also, print the values before setting and check if you are getting the value or not.

print(total_quantity)
print(total_amount)
self.total_amount = total_amount # you can also use this approach to set values
self.total_quantity = total_quantity # you can also use this approach to set values

Here no need of declaring new variables, you can approach like this
self.total_quantity = 0
self.total_amount = 0

and then inside the loop

self.total_quantity += flt(item.number_of_item)
self.total_amount += flt(item.amount)