Home > OS >  I'm stumped trying to figure out how to get the sum of all active and inactive investment balan
I'm stumped trying to figure out how to get the sum of all active and inactive investment balan

Time:06-20

I am trying to query "locked_total_balance":

   locked_total_balance = Investment.objects.filter(is_active=True).aggregate(
        total_balance=Sum('balance'))

and "total_available_balance":

    total_available_balance = Investment.objects.filter(is_active=False).aggregate(
        total_balance=Sum('balance'))

but its not working.

Here is my model

class Investment(models.Model):
    PLAN_CHOICES = (
        ("Basic - Daily 2% for 180 Days", "Basic - Daily 2% for 180 Days"),
        ("Premium - Daily 4% for 360 Days", "Premium - Daily 4% for 360 Days"),
    )
    user = models.ForeignKey(
        User, on_delete=models.CASCADE, null=True, blank=True)
    plan = models.CharField(max_length=100, choices=PLAN_CHOICES, null=True)
    deposit_amount = models.IntegerField(default=0, null=True)
    basic_interest = models.IntegerField(default=0, null=True)
    premium_interest = models.IntegerField(default=0, null=True)
    investment_return = models.IntegerField(default=0, null=True)
    withdraw_amount = models.IntegerField(default=0, null=True, blank=True)
    balance = models.IntegerField(default=0, null=True, blank=True)
    locked_balance = models.IntegerField(default=0, null=True, blank=True)
    investment_id = models.CharField(max_length=10, null=True, blank=True)
    is_active = models.BooleanField(default=False)
    created_at = models.DateTimeField(auto_now=True, null=True)
    due_date = models.DateTimeField(null=True)


    def __str__(self):
        return str(self.investment_id)

CodePudding user response:

The query seems right, maybe you haven't imported Sum() from django.db.models.

Try this:

views.py

from appname.models import Investment

from django.db.models import Sum


def anyview(request):
    locked_total_balance = Investment.objects.filter(is_active=True).aggregate(
        total_balance=Sum('balance'))
    total_available_balance = Investment.objects.filter(is_active=False).aggregate(
        total_balance=Sum('balance'))
    print('------------------------------------------------------')
    print(locked_total_balance)
    print(total_available_balance)
    print('------------------------------------------------------')

    return HttpResponse('it is response')

CodePudding user response:

Here is where the problem originated:

    locked_total_balance = Investment.objects.filter(is_active=True).aggregate(
        total_balance=Sum('balance'))

The total_balance=Sum('balance')) should be locked_total_balance=Sum('balance')).

This fixed the issue.

  • Related