Я в тупике, пытаясь понять, как получить сумму всех активных и неактивных инвестиционных балансов с помощью Django
Я пытаюсь запросить "locked_total_balance"
locked_total_balance = Investment.objects.filter(is_active=True).aggregate(
total_balance=Sum('balance'))
и "total_available_balance"
total_available_balance = Investment.objects.filter(is_active=False).aggregate(
total_balance=Sum('balance'))
но он не работает.
Вот моя модель
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)
Запрос кажется правильным, возможно, вы не импортировали Sum()
из django.db.models
.
Попробуйте это:
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')
Вот где возникла проблема:
locked_total_balance = Investment.objects.filter(is_active=True).aggregate(
total_balance=Sum('balance'))
должно быть total_balance=Sum('balance'))
locked_total_balance=Sum('balance'))
.
Это устранило проблему.