【问题标题】:How to get the sum of all active and inactive investment balances using Django?如何使用 Django 获取所有活跃和非活跃投资余额的总和?
【发布时间】:2022-08-16 00:06:57
【问题描述】:

我正在尝试查询“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()了吗?
  • 我导入了 Sum()

标签: python django django-models django-views django-queryset


【解决方案1】:

查询似乎是对的,可能你还没有从django.db.models 导入Sum()

尝试这个:

视图.py

从 appname.models 导入投资从 django.db.models 导入 Sumdef anyview(请求):
    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('这是响应')

【讨论】:

    【解决方案2】:

    这是问题的根源:

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

    total_balance=Sum('balance'))应该是locked_total_balance=Sum('balance'))

    这解决了这个问题。

    【讨论】:

    • 是的,无论如何这可能是问题,但我还没有看到模板,所以我以为你没有导入 sum(),实际上我担心我是否需要告诉,因为我提供的内容很正常一个答案。从下次开始记得分享所有相关代码:)
    • @SunderamDubey 表示感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-12
    • 1970-01-01
    • 2012-02-04
    相关资源
    最近更新 更多