utils.py 1.4 KB

1234567891011121314151617181920212223242526272829303132
  1. def add_categories_to_threads(root_category, categories, threads):
  2. categories_dict = {}
  3. for category in categories:
  4. categories_dict[category.pk] = category
  5. top_categories_map = {}
  6. for thread in threads:
  7. thread.top_category = None
  8. thread.category = categories_dict[thread.category_id]
  9. if thread.category == root_category:
  10. continue
  11. elif thread.category.parent_id == root_category.pk:
  12. thread.top_category = thread.category
  13. elif thread.category_id in top_categories_map:
  14. thread.top_category = top_categories_map[thread.category_id]
  15. elif root_category.has_child(thread.category):
  16. # thread in subcategory resolution
  17. for category in categories:
  18. if (category.parent_id == root_category.pk and
  19. category.has_child(thread.category)):
  20. top_categories_map[thread.category_id] = category
  21. thread.top_category = category
  22. else:
  23. # global thread in other category resolution
  24. for category in categories:
  25. if category.level == 1 and (
  26. category == thread.category or
  27. category.has_child(thread.category)):
  28. top_categories_map[thread.category_id] = category
  29. thread.top_category = category