Home > other >  Multiplying three models in django and getting the result in views
Multiplying three models in django and getting the result in views

Time:10-25

My model:

class VisData(models.Model):
visdata_id = models.AutoField(primary_key=True,blank=True)
user_name = models.ForeignKey(Customer, null=True, on_delete=models.SET_NULL,blank=True)
title = models.CharField(max_length=200, null=True,blank=True)
buy_sell = models.CharField(max_length=1, null=True,blank=True)
date = models.DateField(auto_now_add=False,null=True,editable=True,blank=True)
hour = models.TimeField(auto_now=False, auto_now_add=False,null=True,editable=True,blank=True)
shares_number = models.DecimalField(decimal_places=0,default=0,max_digits=999,null=True,blank=True)
course = models.DecimalField(decimal_places=2,default=0,max_digits=999,null=True,blank=True)
fare = models.DecimalField(decimal_places=2,default=0,max_digits=999,null=True,blank=True)


def __str__(self):
    return self.title

I want to assign:

total_value = (shares_number * (course - fare)) and just print it in terminal

My views:

def summaryPage(request):
visdata = VisData.objects.all()
#print(visdata)

context = {}
return render(request, 'smth/homepage.html', context)

I found some close answers but I couldn't understand the solution nor use them in my code.

CodePudding user response:

What you probably need called aggregation:

from django.db.models import F, Sum


def summaryPage(request):
    aggregated_data = VisData.objects.annotate(
       intermid_result=F('course') - F('fare')
    ).annotate(
       record_total=F('shares_number') * F('intermid_result')
    ).aggregate(
       total=SUM('record_total')
    )
    result = aggregated_data['total']
    print(result)
    ...

This query will annotate each record with the value of record_total = shares_number * (course - fare) and then calculate a sum for record_total of all records.

Also try to avoid using camelcase function names in Python. See here for details.

  • Related