subscriptions.py 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. from .models import Subscription
  2. __all__ = ['make_subscription_aware']
  3. def make_subscription_aware(user, target):
  4. if hasattr(target, '__iter__'):
  5. make_threads_subscription_aware(user, target)
  6. else:
  7. make_thread_subscription_aware(user, target)
  8. def make_threads_subscription_aware(user, threads):
  9. if not threads:
  10. return
  11. if user.is_anonymous():
  12. for thread in threads:
  13. thread.subscription = None
  14. else:
  15. threads_dict = {}
  16. for thread in threads:
  17. thread.subscription = None
  18. threads_dict[thread.pk] = thread
  19. subscriptions_queryset = user.subscription_set.filter(
  20. thread_id__in=threads_dict.keys()
  21. )
  22. for subscription in subscriptions_queryset.iterator():
  23. threads_dict[subscription.thread_id].subscription = subscription
  24. def make_thread_subscription_aware(user, thread):
  25. if user.is_anonymous():
  26. thread.subscription = None
  27. else:
  28. try:
  29. thread.subscription = user.subscription_set.get(thread=thread)
  30. except Subscription.DoesNotExist:
  31. thread.subscription = None