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.

custom.py 1.9KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. from django.core import exceptions
  2. from oscar.apps.offer.models import Range, Condition, Benefit
  3. def _class_path(klass):
  4. return '%s.%s' % (klass.__module__, klass.__name__)
  5. def create_range(range_class):
  6. """
  7. Create a custom range instance from the passed range class
  8. This function creates the appropriate database record for this custom
  9. range, including setting the class path for the custom proxy class.
  10. """
  11. if not hasattr(range_class, 'name'):
  12. raise exceptions.ValidationError(
  13. "A custom range must have a name attribute")
  14. # Ensure range name is text (not ugettext wrapper)
  15. if range_class.name.__class__.__name__ == '__proxy__':
  16. raise exceptions.ValidationError(
  17. "Custom ranges must have text names (not ugettext proxies)")
  18. # In Django versions further than 1.6 it will be update_or_create
  19. # https://docs.djangoproject.com/en/dev/ref/models/querysets/#update-or-create # noqa
  20. values = {
  21. 'name': range_class.name,
  22. 'proxy_class': _class_path(range_class),
  23. }
  24. try:
  25. obj = Range.objects.get(**values)
  26. except Range.DoesNotExist:
  27. obj = Range(**values)
  28. else:
  29. for key, value in values.iteritems():
  30. setattr(obj, key, value)
  31. obj.save()
  32. return obj
  33. def create_condition(condition_class):
  34. """
  35. Create a custom condition instance
  36. """
  37. return Condition.objects.create(
  38. proxy_class=_class_path(condition_class))
  39. def create_benefit(benefit_class):
  40. """
  41. Create a custom benefit instance
  42. """
  43. # The custom benefit_class must override __unicode__ and description to
  44. # avoid a recursion error
  45. if benefit_class.description is Benefit.description:
  46. raise RuntimeError("Your custom benefit must implement its own "
  47. "'description' property")
  48. return Benefit.objects.create(
  49. proxy_class=_class_path(benefit_class))