utils.py 914 B

12345678910111213141516171819202122
  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.category = categories_dict[thread.category_id]
  8. if thread.category == root_category:
  9. thread.top_category = None
  10. elif thread.category.parent_id == root_category.pk:
  11. thread.top_category = thread.category
  12. elif thread.category_id in top_categories_map:
  13. thread.top_category = top_categories_map[thread.category_id]
  14. else:
  15. for category in categories:
  16. if (category.parent_id == categories[0].pk and
  17. category.has_child(thread.category)):
  18. top_categories_map[thread.category_id] = category
  19. thread.top_category = category