2017-03-04 61 views
0
計算模型字段

我想問一個用戶在一個CreateView中的單個字段中的單個數據,並從該字段計算剩餘模型字段的值。

因此,我可以不問他們所有的數據,而只是要求一件事,然後計算其餘的。

一個基本的例子:

Model.py

class EggCount(models.Model): 
    crates = models.IntegerField() 
    cartons = models.IntegerField() 
    eggs = models.IntegerField() 

Views.py

class EggCountCreateView(generic.CreateView): 
    model = models.EggCount 
    fields = ['crates'] 
    template_name = 'egg_form.html' 

相關的數學,我要用來填寫 '紙箱' 和「雞蛋'模型中的字段。

cartons = crates * 50 
eggs = cartons * 12 

這個數學在Django去哪裏?在模型中?作爲視圖中form_valid函數的一部分?我應該保持它以某種方式分開從模型或視圖中調用它嗎?

對不起,但我完全失去了,很難找到明確的答案,爲此最好的方法。

回答

0

您可以使用這樣的隱藏表單域您egg_form.html

<input type="hidden" name="cartons" value=""> <input type="hidden" name="eggs" value="">

和使用JavaScript/jQuery來執行你的計算和存儲結果的價值屬性。

+0

感謝您的建議,凱文。我希望在這裏嚴格使用Django/Python。爲了清晰起見,這是我的真實代碼的簡化版本。真正的代碼已經有幾個已經在python中構建的公式,我想利用它。 – Dan

0

在沒有看到代碼的其餘部分,我認爲你需要做這樣的事情,把你的數學函數的模型中,然後從視圖中調用它們,然後做任何你需要與他們:

模型的.py

class EggCount(models.Model): 
    crates = models.IntegerField() 
    cartons = models.IntegerField() 
    eggs = models.IntegerField() 

    def cartons(self): 
     cartons = self.crates * 50 

    def eggs(self): 
     eggs = self.cartons * 12 

views.py

class EggCountCreateView(generic.CreateView): 
    model = models.EggCount 
    fields = ['crates'] 
    templates_name = 'egg_form.html' 
    # call the functions within the view 
    cartons = model.cartons() 
    eggs = model.eggs() 
    #then you can do something with the results 
+0

謝謝@ pasta1020。這是一個有趣的方法。我做了類似的事情,但不是添加到模型中,而是創建了一個包含方程的services.py文件,然後從視圖的form_valid中調用該邏輯。我很樂意聽取相反的觀點,但爲什麼這是一個糟糕的做法。 – Dan