Django manytomanyfield模型错误AttributeError:' Order'对象没有属性' item_set'

时间:2014-12-10 19:40:41

标签: django loops model

我的Django模型看起来像这样:

class Item(models.Model):
 title = models.TextField()
 price = models.DecimalField(max_digits=5, decimal_places=2)
 description = models.TextField()
 menu = models.ForeignKey('Menu')

 def __unicode__(self):
     return self.title

class Order(models.Model):
    item = models.ManyToManyField('Item')
    customer = models.ForeignKey('customer.Customer')
    bulkOrder = models.ForeignKey('BulkOrder', default=0)

    @property
    def price(self):
       total = 0
       for item in self.item.all():
           total+=item.price
       return total

当我跑步时:

I1 = Item(title="Phad Thai", price=7.3, description="Skinny noddles", menu=M1)
I1.save()
O1 = Order(customer=C1, bulkOrder=B1)
O1.item.add(I1)
O1.save()
O1.price

      34         def price(self):
      35          total = 0
  --->36          for item in self.item.all():
      37              total+=item.price
                  return total

      AttributeError: 'Order' object has no attribute 'item_set'

但如果我在shell中这样做:

IN: O1.item.all()
OUT: [<Item: Phad See Ew>, <Item: Phad Thai>]

我在StackOverflow上看过类似的例子,但它们与我的问题有点不同

0 个答案:

没有答案