You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1234567891011121314151617181920212223242526272829303132333435
  1. from decimal import Decimal as D
  2. from django.core.exceptions import ObjectDoesNotExist
  3. class Scale(object):
  4. """
  5. For calculating the weight of a product or basket
  6. """
  7. def __init__(self, attribute_code='weight', default_weight=None):
  8. self.attribute = attribute_code
  9. self.default_weight = default_weight
  10. def weigh_product(self, product):
  11. weight = None
  12. try:
  13. weight = product.get_attribute_values().get(
  14. attribute__code=self.attribute).value
  15. except ObjectDoesNotExist:
  16. pass
  17. if weight is None:
  18. if self.default_weight is None:
  19. raise ValueError(
  20. "No attribute %s found for product %s" % (
  21. self.attribute, product))
  22. weight = self.default_weight
  23. return D(weight) if weight is not None else D('0.0')
  24. def weigh_basket(self, basket):
  25. weight = D('0.0')
  26. for line in basket.all_lines():
  27. weight += self.weigh_product(line.product) * line.quantity
  28. return weight