我工作在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