0

这适用于python IDLE

class A:
    b = 0

    def __init__(self, value):
        self.b = value

obj1 = A(1)
obj2 = A(2)
obj3 = A(3)
k = [obj1, obj2, obj3]
result = sum(i.b for i in k)
print str(result)

但这不适用于 django/python

from django.db import models

class Flatbar(models.Model):
    width = models.IntegerField()
    height = models.IntegerField()

    def Area(self):
        return self.width * self.height

class Section(models.Model):
    flatbars = models.ManyToManyField(Flatbar)

    def Area(self):
        return str(sum(f.Area for f in self.flatbars))

为什么这不起作用,我将如何使用 lambda 函数来做到这一点?

4

1 回答 1

3

a 的属性ManyToManyField产生了一个管理器,并且您创建了Area一个方法。

return str(sum(f.Area() for f in self.flatbars.all()))
于 2013-01-17T20:27:07.517 回答