2016-11-04 33 views
-2

以下是相關的應用程序和課程。嘗試獲取屬於發票的所有組件的總和並將其保存在發票的'sub_total'字段中。發票sub_total =發票實例所有組件的總和。什麼將會被解決?提前致謝。django內聯課程價格的總和

from stock.models import Part 


class Invoice(models.Model): 
    invoice_number = models.CharField(max_length=250) 
    sub_total = models.DecimalField(max_digits=8, decimal_places=2) 


class Component(models.Model):   
    invoice = models.ForeignKey('Invoice',) 
    stock = models.ForeignKey('stock.Part',) 
    qty = models.SmallPositiveIntegerField() 
    unit_price = models.DecimalField(max_digits=8, decimal_places=2) 
    amount = models.DecimalField(max_digits=8, decimal_places=2) 
+1

向我們展示你的看法和你有什麼,直到這點做?錯誤即將到來。不要指望我們爲你做你的工作。 –

+0

只是希望得到一個線索,就是這樣。像這樣的東西可能不需要觀點 - 簡單地在models.py中完成 - 那是我所希望的。 – sunjoo

回答

0

經過幾個小時的嘗試,我終於得到了一個線索,現在的事情工作正常。我不想在視圖或模板中使用複雜的東西。

下面的鏈接有一個很好的例子,從下面學習和進一步的測試似乎工作正常。

https://github.com/mwolff44/django-simple-invoice/blob/master/invoice/models.py 圍繞行號194,類似如下圖所示,它告訴我們的線索,該怎麼做。

下面是類似我的 「發票」 類....

def total(self): 
    total = Decimal('0.00') 
    for item in self.items.all(): 
     total = total + item.total() 
    return total 

然後在項目(組件,在我的情況)類。大約在第281行,顯示如下所示。儘管早些時候這已經得到了照顧,但其他人可能認爲這很有用。 ...

def total(self): 
    total = Decimal(str(self.unit_price * self.quantity)) 
    return total.quantize(Decimal('0.01')) 

再次,非常感謝馬蒂亞斯·沃爾夫https://github.com/mwolff44