Search code examples
djangodjango-modelsdjango-viewsdjango-templatesdjango-datatable

Pass a filtered field to views.py for further operation


I'm pretty new to Django working in a small project. I need to have the logged in user to be able to see the total of taxes. In the user model is every users info, including each of these taxes, I need to have them called in the views.py so I can use it for further operation with other variables. So far I've been able to Sum .filter() and .all() fields in the same column or field, but cant see to find a way to Sum or call different fields of same row.

models.py

class User(AbstractUser):
    username = models.CharField(unique=True, max_length=20, null=True)
    email = models.EmailField(null=True)
    tax1 = models.DecimalField(max_digits=7, decimal_places=2, default=0)
    tax2 = models.DecimalField(max_digits=7, decimal_places=2, default=0)
    tax3 = models.DecimalField(max_digits=7, decimal_places=2, default=0)

views.py

def Calc(request):
    m_tax1 = User.objects.filter(username=request.user)
    m_tax11 = m_tax1.aggregate(Sum('tax_1'))
    m_tax2 = User.objects.filter(username=request.user)
    m_tax22 = m_tax2.aggregate(Sum('tax_2'))
    m_tax3 = User.objects.filter(username=request.user)
    m_tax33 = m_tax2.aggregate(Sum('tax_3'))
    total_tax = m_tax11 + m_tax22 + m_tax33 

    context = {
    'm_tax11' : m_tax11,
    'm_tax22' : m_tax22,
    'm_tax33' : m_tax33,
    'total_tax' : total_tax}

    return render(request,'main/calc.html', context)

template

{{m_tax11}}
+
{{m_tax22}}
+
{{m_tax33}}
=
{{total_tax}}

Solution

  • you can add a function to your User model for row level aggregation

    def get_total_taxes(self):
        return self.tax1 + self.tax2 + self.tax3 
    

    and call it from a given User (object)

    print(request.user.get_total_taxes())
    

    and if you want to do it on database level you can annotate a new field

    user_objects = User.objects.filter(username=request.user).annotate(total_tax=F('tax1')+F('tax2')+F('tax3'))
    

    sum multiple rows

    total_tax = user_objects.aggregate(Sum('total_tax'))