Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

custom.py 1.9KB

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