Muhammed Bilal
Muhammed Bilal

Reputation: 399

Calculating two integers fields in django

I want to calculate these fields and want output for example (budget - Expense) (budget + Expense) (budget * Expense). how could i do that.

 Class calculate(models.Model):
       budget = models.IntegerField(default=0)
       Expense = models.IntegerField(default=0)

Upvotes: 0

Views: 353

Answers (2)

Ajay saini
Ajay saini

Reputation: 2470

You can use model method.

Class calculate(models.Model):
       budget = models.IntegerField(default=0)
       Expense = models.IntegerField(default=0)

       def get_budget_total(self):
           return budget + Expenses 

use like model function

claculate_object.get_budget_total()    

and in template file use direct

claculate_object.get_budget_total

FYI use correct naming conventions for naming method and class name for class names use capitalized and for methods and properties use small case

Upvotes: 1

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477170

You can .annotate(..) [Django-doc] your queryset. For example:

from django.db.models import F

Calculate.objects.annotate(
    difference=F('budget') - F('expense'),
    total=F('budget') + F('expense'),
    product=F('budget') * F('expense')
)

The Calculate objects that arise from this will have three extra attributes: .difference, .total and .product that contain the difference, sum and product of budget and expense respectively.

Note: The name of Django models is formatted as CamelCase, so Calculate, instead of calculate. The attributes are formatted lowercase_with_underscore, so expense instead of Expense.

Upvotes: 0

Related Questions