backends.py 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. # -*- coding: utf-8 -*-
  2. """Various helpers designed to help configuration backends regarding
  3. repetitive tasks."""
  4. from django.core.exceptions import ValidationError
  5. from django.db.models import Q
  6. from coin.offers.models import OfferSubscription
  7. class ValidateBackendType(object):
  8. """Helper validator for configuration backends.
  9. It ensures that the related subscription has the right backend
  10. type. This is a bit ugly, as validators are not meant for
  11. database-level sanity checks, but this is the cost of doing genericity
  12. the way we do.
  13. Note that this validator should not be needed for most cases, as the
  14. "limit_choices_to" parameter of the "administrative_subscription"
  15. OneToOneField should automatically limit the available choices on
  16. forms. But it does not protect us if we fiddle manually with the
  17. database: better safe than sorry.
  18. """
  19. def __init__(self, backend_name):
  20. self.backend = backend_name
  21. def __call__(self, subscription):
  22. if OfferSubscription.objects.get(pk=subscription).offer.backend != self.backend:
  23. raise ValidationError('Administrative subscription must have a "{}" backend.'.format(self.backend))
  24. def filter_subscriptions(backend_name, instance):
  25. """Helper function for configuration backends, allowing to filter
  26. subscriptions that have the right """
  27. return Q(offer__backend=backend_name) & (
  28. # Select "unassociated" subscriptions, plus our own
  29. # subscription (in case we are editing the object).
  30. Q((backend_name, None)) | Q((backend_name, instance.pk)))