fix(perf): Avoid extra queries in MonitorEnvironmentSerializer#106428
Merged
fix(perf): Avoid extra queries in MonitorEnvironmentSerializer#106428
Conversation
wedamija
approved these changes
Jan 16, 2026
Comment on lines
+112
to
+128
| # Build date_added mapping, starting with cached monitors | ||
| date_added_by_monitor_id = {} | ||
| uncached_monitor_ids = set[int]() | ||
|
|
||
| for monitor_env in item_list: | ||
| if monitor_env.is_field_cached("monitor"): | ||
| # Extract date_added from cached monitor | ||
| date_added_by_monitor_id[monitor_env.monitor_id] = monitor_env.monitor.date_added | ||
| else: | ||
| # Need to fetch this monitor | ||
| uncached_monitor_ids.add(monitor_env.monitor_id) | ||
|
|
||
| # Batch query for uncached monitors - only fetch date_added field | ||
| if uncached_monitor_ids: | ||
| date_added_by_monitor_id.update( | ||
| Monitor.objects.filter(id__in=uncached_monitor_ids).values_list("id", "date_added") | ||
| ) |
Member
There was a problem hiding this comment.
Nit: No need to change if you don't want to , but a simple way to do this is prefetch_related_objects like
The way you're doing it is more efficient since we bring down fewer fields, but this way is more concise.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to subscribe to this conversation on GitHub.
Already have an account?
Sign in.
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
MonitorEnvironmentSerializer relies on Monitor data, but fetching it via implicit query results in lots of unnecessary queries.
We can avoid this by batch fetching when it isn't cached, and using the cached value when available.
By ensuring the Monitor is cached in MonitorSerializer, where we already have the Monitors, no queries are required.