2016-02-12 53 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