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 个文件,如何获得总金额?


倚天杖
浏览 86回答 1
1回答

偶然的你

我认为您可以将其添加amount为DecimalField模型,并在创建对象后对其进行计算,然后发送post_save信号。然后添加一个简单地汇总所有金额的静态方法。     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()
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python