如何使用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)

查询似乎是正确的,可能您没有从django.db.models导入Sum()

试试这个:

views.py

<>之前从浏览器名称。模型进口 from django.db.modelsdef网络警(请求):locked_total_balance = Investment.objects.filter(is_active=True).aggregate(total_balance =总和('平衡'))total_available_balance = Investment.objects.filter(is_active=False).aggregate(total_balance =总和('平衡'))打印 ('------------------------------------------------------')打印(locked_total_balance)打印(total_available_balance)打印 ('------------------------------------------------------')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'))

修复此问题。

最新更新