subscriptions.py 1.1 KB

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