我工作在Django與產品,價格,統計等工作的Web應用程序Django - 是否可以迭代方法?
編輯: 更簡單明瞭的解釋:如何「集團」或「標記」的一些實例方法,所以我可以迭代他們就像for method in instance.name_of_the_group
爲了保持簡單 - 我有一個型號Product
。 Product
有多個屬性和方法。其中一些方法返回「統計」數據。
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_price
和get_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>
謝謝,但我不明白我怎麼能在上面寫的xml生成器例子中使用它。這些方法應該有像屬性method.programmatic_name(history_average_price爲XML使用)和method.label(歷史AVG價格)用於表生成等。 –
哦,等等,也許我知道。我可以添加屬性到像標籤=等方法 –
是的,就是這樣 - 就像你使用任何函數一樣,真的,但用點符號!如果它足夠普遍,我想你可以將XML片段寫入模型管理器 - 它們不需要返回查詢集。 :) – Withnail