2016-12-09 138 views
3

我工作在Django与产品,价格,统计等工作的Web应用程序Django - 是否可以迭代方法?

编辑: 更简单明了的解释:如何“集团”或“标记”的一些实例方法,所以我可以迭代他们就像for method in instance.name_of_the_group

为了保持简单 - 我有一个型号ProductProduct有多个属性和方法。其中一些方法返回“统计”数据。

class Product(models.Model): 
    name = ... 
    ... 

    def save(... 
    ... 

    def get_all_colors(self): 
    .... 

    def get_historical_average_price(self): #statistic method 
     price = <some calculation> 
     return price 

    def get_historical_minimal_price(self): #statistic method 
     ... 
     return price 

所以有很多像get_historical_average_priceget_historical_minimal_price方法。

现在我必须编写标签并在项目中逐一调用这些方法。例如,当我生成一个表或创建一个XML导出。

我希望能够以某种方式“标记”他们说,这些都是“统计”的方法,给他们一些名称,这样我就可以与他们使用for循环等。

工作有没有一些方法要做到这一点?

例如在XML生成:

<products> 
    {% for product in products %} 
     <product> 
      <code>{{ product.code }}</code> 
      <name>{{ product.name }}</name> 
      <statistics> 
       <historical_average>{{ product.get_historical_average_price}}</historical_average> 
       <minimal_price>{{ product.get_historical_minimal_price}}</minimal_price> 
      </statistics> 
     </product> 
    {% endfor %} 
</products> 

所以我会做这样的事情:

<statistics> 
{% for statistic_method in product.statistics %} 
    <{{ statistic_method.name }}>{{ statistic_method }}</{{ statistic_method.name }}> 
{% endfor %} 
</statistics> 

代替:

<statistics> 
    <historical_average>{{ product.get_historical_average_price}}</historical_average> 
    <minimal_price>{{ product.get_historical_minimal_price}}</minimal_price> 
</statistics> 

回答

0

这是一个伟大的使用情况下,使用自定义model managers因为您可以使用或覆盖他们在那里使用的名称。

所以在你的榜样,是这样的:

class StatisticsManager(models.Manager): 
    def historical_average_price(self): 
     ... 

class Product(models.Model): 
    name = ... 
    statistics = StatisticsManager() 

这将在随后的形式

product_price = Product.statistics.get_historical_average_price

等被调用。

编辑:

我忘了 - 因为你要替换默认objects经理,我认为,你需要明确地重申,作为一个管理者,每this article - 但你可以有一个对象上的多个经理如果需要,所以objects,statistics,otherstuffhere

+0

谢谢,但我不明白我怎么能在上面写的xml生成器例子中使用它。这些方法应该有像属性method.programmatic_name(history_average_price为XML使用)和method.label(历史AVG价格)用于表生成等。 –

+1

哦,等等,也许我知道。我可以添加属性到像标签=等方法 –

+0

是的,就是这样 - 就像你使用任何函数一样,真的,但用点符号!如果它足够普遍,我想你可以将XML片段写入模型管理器 - 它们不需要返回查询集。 :) – Withnail

相关问题