我正在处理Django的Web应用程序,该应用程序与产品,价格和统计等一起工作。
编辑:更多直截了当的解释:如何"组"或"标记"某些实例方法,因此我可以像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 Generator上的示例:
<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>
这是使用自定义模型管理器的绝佳用例,因为您可以使用或覆盖他们在那里使用的名称。
因此,在您的示例中,类似:
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
经理时,我相信您需要明确地将其作为经理,根据本文 - 但是,如果需要,您可以在对象上有多个经理,因此objects
,因此statistics
,otherstuffhere
。