2012-06-05 30 views
0

請如何解決分配前引用的錯誤局部變量'stockqty'?在我的模型,其搜索的項目之一,我有一個保存方法,並返回像數量,價格,成本等一些價值觀,但我不斷收到這個錯誤..在django中分配之前引用的局部變量'stockqty'

高清保存(個體經營):

callitems=Item.objects.filter(subcategory=self.ItemName) 

    for callitem in callitems: 
     stockqty=callitem.quantity 
     #stovkqty.append(callitem.quantity) 
     price=callitem.unitprice 
     #price.append(callitem.unitprice) 
     cost=callitem.unitcost 
     #cost.append(callitem.unitcost) 
     vat=callitem.tax.rate 
    if self.quantity < stockqty: the error complain is here 
     if self.discount==True: 
      self.total= self.discountprice * self.quantity 
      self.profit=self.total-(cost * self.quantity) 
      self.salesdate=date.today() 
      self.salestime=datetime.now() 
      self.staff='admin' 
      Item.objects.filter(subcategory=self.ItemName).update(quantity=stockqty-self.quantity) 
     else: 
      self.total= price * self.quantity 
      self.profit=self.total-(cost * self.quantity) 
      self.salesdate=date.today() 
      self.salestime=datetime.now() 
      self.staff='admin' 
      Item.objects.filter(subcategory=self.ItemName).update(quantity=stockqty-self.quantity) 
    super(RecordSales, self).save() 

回答

2

您可能有縮進錯誤。第一個if語句應該位於for循環內,但它與其「並行」。試試這個:

callitems=Item.objects.filter(subcategory=self.ItemName) 

    for callitem in callitems: 
     stockqty=callitem.quantity 
     #stovkqty.append(callitem.quantity) 
     price=callitem.unitprice 
     #price.append(callitem.unitprice) 
     cost=callitem.unitcost 
     #cost.append(callitem.unitcost) 
     vat=callitem.tax.rate 
     if self.quantity < stockqty: # the error complain is here 
      if self.discount==True: 
       self.total= self.discountprice * self.quantity 
       self.profit=self.total-(cost * self.quantity) 
       self.salesdate=date.today() 
       self.salestime=datetime.now() 
       self.staff='admin' 
       Item.objects.filter(subcategory=self.ItemName).update(quantity=stockqty-self.quantity) 
      else: 
       self.total= price * self.quantity 
       self.profit=self.total-(cost * self.quantity) 
       self.salesdate=date.today() 
       self.salestime=datetime.now() 
       self.staff='admin' 
       Item.objects.filter(subcategory=self.ItemName).update(quantity=stockqty-self.quantity) 
     super(RecordSales, self).save() 
+0

更重要的是,用下面的聯合測試取代連續兩個'if's:'如果self.quantity heltonbiker

相關問題