2016-02-12 57 views
1

我想知道是否可以在ListView的每個記錄上應用規則例如:從模型中獲取以克爲單位的值並創建包含kg值的新var,如果克值> 1000Django:操縱generic.ListView中的數據

我試圖用的get_object但它僅適用於ViewDetail

在此先感謝您的幫助:)

class ViewBsin(generic.ListView): 
template_name = 'browser/bsin.html' 
context_object_name = 'gtin_list' 
model = Gtin 
... 
def get_object(self): 
    # Call the superclass 
    object = super(ViewBsin, self).get_object() 
    # Add new data 
    if object.M_G and object.M_G >= 1000: 
     object.M_KG = object.M_G/1000 
    if object.M_ML and object.M_ML >= 1000: 
     object.M_L = object.M_ML/1000 
    object.save() 
    # Return the object 
return object 
+0

thx!但我必須存儲這些數據,因爲單位是克拉(克),我想顯示爲KiloGram(Kg)..因爲1公斤= 1000克;)...做到這一點的唯一方法是分成模板??但沒有辦法將模板分成:(:(你的答案:)( – Philippos

回答

1

您可以覆蓋通過查詢集get_queryset和循環,更新的對象。您不應該調用save(),因爲這會更新數據庫,並且ListView應該是隻讀的。

class ViewBsin(generic.ListView): 

    def get_queryset(self): 
     queryset = super(ViewBsin, self).get_queryset() 
     for obj in queryset: 
      if obj.M_G and obj.M_G >= 1000: 
       obj.M_KG = obj.M_G/1000 
      # Make any other changes to the obj here 
      # Don't save the obj to the database -- ListView should be read only 
     return queryset 

另一種方法是編寫custom filter將克轉換爲千克。接着的,在你的模板,而不是寫

{{ object.M_KG }} 

你會做

{{ object.M_G|to_kg }} 

如果您有更多的自定義邏輯,像 '顯示KG如果g> 1000,否則顯示G' ,那麼這些都可以在模板過濾器中進行。這簡化了您的模板,並將顯示邏輯保持在視圖之外。

+0

thx很多:) – Philippos