Reduce a number of requests to db on alert_receive_channel internal api endpoint (#4805)

# What this PR does
Reduce a number of requests to db on `alert_receive_channel` internal
api endpoint
from
<img width="348" alt="Screenshot 2024-08-12 at 14 55 05"
src="https://github.com/user-attachments/assets/fcbadfaf-4f01-40ae-879a-86115e13984d">
to
<img width="341" alt="Screenshot 2024-08-12 at 14 55 13"
src="https://github.com/user-attachments/assets/4fbdc3f8-297a-44ed-acfa-41f6245b2a5e">

## Which issue(s) this PR closes

Related to [issue link here]

<!--
*Note*: If you want the issue to be auto-closed once the PR is merged,
change "Related to" to "Closes" in the line above.
If you have more than one GitHub issue that this PR closes, be sure to
preface
each issue link with a [closing
keyword](https://docs.github.com/en/get-started/writing-on-github/working-with-advanced-formatting/using-keywords-in-issues-and-pull-requests#linking-a-pull-request-to-an-issue).
This ensures that the issue(s) are auto-closed once the PR has been
merged.
-->

## Checklist

- [ ] Unit, integration, and e2e (if applicable) tests updated
- [x] Documentation added (or `pr:no public docs` PR label added if not
required)
- [x] Added the relevant release notes label (see labels prefixed w/
`release:`). These labels dictate how your PR will
    show up in the autogenerated release notes.
This commit is contained in:
Yulya Artyukhina 2024-08-13 11:24:30 +02:00 committed by GitHub
parent b3119e5266
commit 18726432af
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -12,7 +12,6 @@ from rest_framework.fields import SerializerMethodField
from apps.alerts.grafana_alerting_sync_manager.grafana_alerting_sync import GrafanaAlertingSyncManager
from apps.alerts.models import AlertReceiveChannel
from apps.alerts.models.channel_filter import ChannelFilter
from apps.base.messaging import get_messaging_backends
from apps.integrations.legacy_prefix import has_legacy_prefix
from apps.labels.models import LabelKeyCache, LabelValueCache
@ -277,7 +276,7 @@ class AlertReceiveChannelSerializer(
# With using of select_related ORM builds strange join
# which leads to incorrect heartbeat-alert_receive_channel binding in result
PREFETCH_RELATED = ["channel_filters", "integration_heartbeat", "labels", "labels__key", "labels__value"]
SELECT_RELATED = ["organization", "author"]
SELECT_RELATED = ["organization", "author", "team"]
class Meta:
model = AlertReceiveChannel
@ -490,11 +489,12 @@ class AlertReceiveChannelSerializer(
return has_legacy_prefix(obj.integration)
def get_connected_escalations_chains_count(self, obj: "AlertReceiveChannel") -> int:
return (
ChannelFilter.objects.filter(alert_receive_channel=obj, escalation_chain__isnull=False)
.values("escalation_chain")
.distinct()
.count()
return len(
set(
channel_filter.escalation_chain_id
for channel_filter in obj.channel_filters.all()
if channel_filter.escalation_chain_id is not None
)
)