django models.py中的Python

时间:2013-01-17 20:23:25

标签: python django lambda sum

这适用于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函数执行此操作?

1 个答案:

答案 0 :(得分:3)

ManyToManyField的属性会产生一个经理,并且您将Area作为方法。

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