Skip to content Skip to sidebar Skip to footer

Django - Is It Possible To Iterate Over Methods?

I'm working on a Web Application in Django which works with products, prices and statistics etc. EDIT: More straighforward explanation: How to 'group' or 'mark' some of instance m

Solution 1:

This is a great use case for using custom model managers as you can use or override the names that they use there.

So in your example, something like :

class StatisticsManager(models.Manager):
    def historical_average_price(self):
        ...

class Product(models.Model):
    name = ... 
    statistics = StatisticsManager()

Which would then be called in the form

product_price = Product.statistics.get_historical_average_price

and so on.

Edit:

I forgot - as you're overriding the default objects manager, I believe that you'll need to explicitly restate that as a manager, per this article - but you can have multiple managers on an object if desired, so objects, statistics, otherstuffhere.


Post a Comment for "Django - Is It Possible To Iterate Over Methods?"