Skip to content

Commit

Permalink
Minor query optimizations (#4325)
Browse files Browse the repository at this point in the history
Related to some API latency issues we were noticing.
  • Loading branch information
matiasb authored May 8, 2024
1 parent bdbff82 commit 01cb87c
Show file tree
Hide file tree
Showing 2 changed files with 1 addition and 20 deletions.
9 changes: 0 additions & 9 deletions engine/apps/alerts/models/alert_group.py
Original file line number Diff line number Diff line change
Expand Up @@ -511,17 +511,8 @@ def slack_app_link(self) -> typing.Optional[str]:

@property
def telegram_permalink(self) -> typing.Optional[str]:
"""
This property will attempt to access an attribute, `prefetched_telegram_messages`, representing a list of
prefetched telegram messages. If this attribute does not exist, it falls back to performing a query.
See `apps.public_api.serializers.incidents.IncidentSerializer.PREFETCH_RELATED` as an example.
"""
from apps.telegram.models.message import TelegramMessage

if hasattr(self, "prefetched_telegram_messages"):
return self.prefetched_telegram_messages[0].link if self.prefetched_telegram_messages else None

main_telegram_message = self.telegram_messages.filter(
chat_id__startswith="-", message_type=TelegramMessage.ALERT_GROUP_MESSAGE
).first()
Expand Down
12 changes: 1 addition & 11 deletions engine/apps/public_api/serializers/incidents.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
from django.db.models import Prefetch
from rest_framework import serializers

from apps.alerts.models import AlertGroup
from apps.telegram.models.message import TelegramMessage
from common.api_helpers.custom_fields import UserIdField
from common.api_helpers.mixins import EagerLoadingMixin

Expand All @@ -19,14 +17,6 @@ class IncidentSerializer(EagerLoadingMixin, serializers.ModelSerializer):
resolved_by = UserIdField(read_only=True, source="resolved_by_user")

SELECT_RELATED = ["channel", "channel_filter", "slack_message", "channel__organization"]
PREFETCH_RELATED = [
"alerts",
Prefetch(
"telegram_messages",
TelegramMessage.objects.filter(chat_id__startswith="-", message_type=TelegramMessage.ALERT_GROUP_MESSAGE),
to_attr="prefetched_telegram_messages",
),
]

class Meta:
model = AlertGroup
Expand All @@ -50,7 +40,7 @@ def get_title(self, obj):
return obj.web_title_cache

def get_alerts_count(self, obj):
return len(obj.alerts.all())
return obj.alerts.count()

def get_state(self, obj):
return obj.state
Expand Down

0 comments on commit 01cb87c

Please sign in to comment.