Skip to content
6 changes: 6 additions & 0 deletions openedx_tagging/core/tagging/models/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -372,6 +372,12 @@ def copy(self, taxonomy: Taxonomy) -> Taxonomy:
self.visible_to_authors = taxonomy.visible_to_authors
self.export_id = taxonomy.export_id
self._taxonomy_class = taxonomy._taxonomy_class # pylint: disable=protected-access

# Copy Django's internal prefetch_related cache to reduce queries required on the casted taxonomy.
if hasattr(taxonomy, '_prefetched_objects_cache'):
# pylint: disable=protected-access,attribute-defined-outside-init
self._prefetched_objects_cache: dict = taxonomy._prefetched_objects_cache

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note: I used code from this blog to make this change. That blog post also copies the caches for one-to-many fields that were cached using select_related, but since Taxonomy doesn't have any one-to-many fields, I omitted that part.

return self

def get_filtered_tags(
Expand Down
2 changes: 1 addition & 1 deletion openedx_tagging/core/tagging/rest_api/v1/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -252,7 +252,7 @@ def get_queryset(self) -> models.QuerySet:
query_params.is_valid(raise_exception=True)
enabled = query_params.data.get("enabled", None)

return get_taxonomies(enabled)
return get_taxonomies(enabled).prefetch_related('tag_set')

def perform_create(self, serializer) -> None:
"""
Expand Down
2 changes: 1 addition & 1 deletion tests/openedx_tagging/core/tagging/test_views.py
Original file line number Diff line number Diff line change
Expand Up @@ -257,7 +257,7 @@ def test_list_taxonomy_query_count(self):
url = TAXONOMY_LIST_URL

self.client.force_authenticate(user=self.user)
with self.assertNumQueries(5):
with self.assertNumQueries(3):
response = self.client.get(url)

assert response.status_code == 200
Expand Down