2016-12-09 56 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

相關問題