May 19, 2010

Python's all() function usage.

Recently I've came across superb python function all(). What it does is just selecting all items,variables,objects,etc fulfilling some requirements. Usage :

all(our_requirement)

Here's my code from Django-LFS (used on purple-cow.pl website). It's a function deactivating products if they have no stocks (also using my function get_stock_amount, which simply returns stocks of product). Still in development though, gotta add some control from management panel.

def deactivate(self):
        """If there are no stocks, deactivate the product. Used in last step of checkout.
        """

        inactive = False
        
        if self.is_variant():
            prod = self.parent
            inactive = all(var.get_stock_amount() == 0 for var in prod.variants.filter(active=True))
            if inactive:
                prod.active = 0
            prod.save()
        else:
            if self.get_stock_amount() == 0:
                self.active = 0
        
            self.save()

No comments:

Post a Comment