“TypeError:/:不支持的操作数类型'str'和'int'“在从Django模型分割字段时

9lowa7mx  于 2023-08-08  发布在  Go
关注(0)|答案(1)|浏览(110)

我试图计算一个用户在Django模型中设定的货币目标取得了多少进展,但它一直给我这个错误:
第一个月
这就是我试图计算用户进度的方法:

def calculateGoalPercentage(self):
    onePercent = self.goal / 100
    goalPercentage = self.calculateBalance() / onePercent

    return goalPercentage

字符串
这是我的模型:

class Space(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=30, default="New Space")

    balance = models.FloatField(default=0.00)
    goal = models.FloatField(default=100.00, validators=[MinValueValidator(1.00)])

    typeChoices = [
        (0, "Private"),
        (1, "Shared"),
    ]
    space_type = models.CharField(max_length=7, choices=typeChoices, null=True, blank=True)

    owner = models.ForeignKey(to=User, on_delete=models.CASCADE, blank=True, null=True)
    created = models.DateField(auto_now=True)

    records = models.ManyToManyField(Record, blank=True, default=None)

    notes = models.TextField(default="")
    
    def calculateBalance(self):
        total = 0

        for record in self.records.all():
            total += record.amount

        return total

    def calculateGoalPercentage(self):
        onePercent = self.goal / 100
        goalPercentage = self.calculateBalance() / onePercent

        return goalPercentage

    def __str__(self):
        return self.name


下面是Record模型:

class Record(models.Model):
    id = models.AutoField(primary_key=True)
    added = models.DateTimeField(auto_now=True)
    amount = models.FloatField()
    memo = models.CharField(max_length=50, default="-")

    def __str__(self):
        name = "Record on " + str(self.added)
        return name
    
    def getName(self):
        name = "Record on " + str(self.added)
        return name


有人知道发生什么事了吗这似乎是一个错误,我会发现回来当我是一个初学者,所以我认为我错过了一个小细节。

cunj1qz1

cunj1qz11#

self.goal渲染字符串,但在模型中它是float字段,所以,只需将self.goal改为float字段即可。

def calculateGoalPercentage(self):
    goal_value = float(self.goal)
    onePercent = goal_value / 100
    goalPercentage = self.calculateBalance() / onePercent
    return goalPercentage

字符串

相关问题