Skip to content

fix(managers): utilize prefetch cache in names() and slugs() (#936) - #952

Open
SparshGarg999 wants to merge 1 commit into
jazzband:masterfrom
SparshGarg999:fix-936-names-slugs-prefetch-cache
Open

fix(managers): utilize prefetch cache in names() and slugs() (#936)#952
SparshGarg999 wants to merge 1 commit into
jazzband:masterfrom
SparshGarg999:fix-936-names-slugs-prefetch-cache

Conversation

@SparshGarg999

Copy link
Copy Markdown

Fixes #936

Problem

Calling .names() or .slugs() on a _TaggableManager on model instances loaded via prefetch_related("tags") executed new SQL queries (values_list()) instead of leveraging the prefetched tags stored in memory in _prefetched_objects_cache. This resulted in unexpected N+1 query loops despite prefetching.

Solution

  • Updated names() and slugs() in _TaggableManager (taggit/managers.py) to inspect _prefetched_objects_cache on the instance and extract tag names/slugs directly from cached tag instances if available, avoiding extra DB queries.
  • Retained standard queryset values_list() evaluation when prefetch cache is not present.
  • Added unit test test_names_and_slugs_use_prefetch_cache to TestPrefetchCache in tests/test_models.py verifying 0 SQL queries are executed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

TaggableManager.names() does not use the prefetch cache

1 participant