gpt4 book ai didi

python - Django - 是否可以迭代方法?

转载 作者:行者123 更新时间:2023-11-28 19:10:29 24 4
gpt4 key购买 nike

我正在使用 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 生成器示例:

<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>

最佳答案

这是使用自定义 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 作为管理器明确重申这一点- 但如果需要,您可以在一个对象上拥有多个管理器,因此 objectsstatisticsotherstuffhere

关于python - Django - 是否可以迭代方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41063566/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com