Django – Excel 计算方法的总和值

我创建了一个数据模型,让用户上传excel文件并计算行和列。

class Data(models.Model):
    """ Model of Data"""
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    document = models.FileField(upload_to="documents/%Y/%m/%d")
    uploaded_at = models.DateTimeField(auto_now_add=True)

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

    def amount(self):
        wb = xlrd.open_workbook(self.document.name)
        worksheet = wb.sheet_by_index(0)

        row_count = worksheet.nrows
        print(row_count)
        column_count = worksheet.ncols
        print(column_count)

        total_col_row = row_count * column_count

        # print payments
        payments = total_col_row * 9

        return payments

如何获得总金额,如果用户输入例如3个文件?

解决方案:

我认为你可以添加 amount 作为 DecimalField 的模型,并在创建你的对象后计算它,thankx to post_save signal.然后添加一个静态方法,简单地将所有金额相加。

     from django.db.models import Sum
     from django.dispatch import receiver

     class Data(models.Model):
                """ Model of Data"""
                user = models.ForeignKey(User, on_delete=models.CASCADE)
                document = models.FileField(upload_to="documents/%Y/%m/%d")
                uploaded_at = models.DateTimeField(auto_now_add=True)
                amount = models.DecimalField(default=0, max_digits=4, decimal_places=2, blank=True, null=True)

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

              @property
               def total_amount():
                    return Data.objects.all().aggregate(Sum('amount '))['amount __sum']

                def calculate_amount(self):
                    wb = xlrd.open_workbook("documents/%Y/%m/%d"+self.document.name)
                    ...

  @receiver(post_save, sender=Data)
   def data_amount_post_save(sender, instance, created, **kwargs):
   instance.amount= instance.calculate_amount()
   instance.save()

给TA打赏
共{{data.count}}人
人已打赏
未分类

使用lambda部署上传lambda函数时,生成zip文件出错。

2022-9-9 16:41:22

未分类

如何将用户输入的内容设置为状态?

2022-9-9 16:52:18

0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索