How to Fix Django's GenericForeignKey N+1 Query Problem Without Schema Changes
Django's GenericForeignKey (GFK) fields, commonly used in audit logs and notification feeds, cannot be traversed by the ORM's select_related or prefetch_related, causing one database query per object lookup. On a page of 20 activity log entries, this can quickly balloon to 60–80 queries before pagination is even considered. A three-step workaround resolves all GFK references in bulk by grouping object IDs by content type and firing a single query per target model. The resolved instances are then cached on each log entry as a private attribute, allowing serializers to read from cache with a live-query fallback. This approach requires no model or schema changes, making it suitable for inherited codebases where migrations are not an option.
This is an AI-generated summary. ShortSingh links to the original source for the complete article.
Discussion (0)
Log in to join the discussion and vote.
Log in