Skip to content

Commit bb4b9f1

Browse files
authored
perf(attachments): access XForm directly from Attachment to avoid heavy joins on Instance table (#6488)
### 📣 Summary Improve performance by linking attachments directly to their project. ### 📖 Description This optimization allows retrieving the related `XForm` directly from the `Attachment` model, bypassing the need to join through the `Instance` table, which can be extremely large. By establishing a more direct relationship, the system reduces query complexity and execution time, significantly improving performance when loading or filtering attachments.
1 parent 3edb2b0 commit bb4b9f1

File tree

3 files changed

+4
-6
lines changed

3 files changed

+4
-6
lines changed

kobo/apps/openrosa/apps/logger/signals.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -44,8 +44,7 @@ def pre_delete_attachment(instance, **kwargs):
4444
attachment = instance
4545
file_size = attachment.media_file_size
4646
only_update_counters = kwargs.pop('only_update_counters', False)
47-
# TODO use deserialized XForm from Attachment model
48-
xform = attachment.instance.xform
47+
xform = attachment.xform
4948
user_id = xform.user_id
5049

5150
if file_size and attachment.delete_status is None:
@@ -100,8 +99,7 @@ def post_save_attachment(instance, created, **kwargs):
10099
if not file_size:
101100
return
102101

103-
# TODO use deserialized XForm from Attachment model
104-
xform = attachment.instance.xform
102+
xform = attachment.xform
105103
user_id = xform.user_id
106104

107105
update_storage_counters(xform.pk, user_id, file_size)

kobo/apps/openrosa/apps/viewer/views.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -247,7 +247,7 @@ def attachment_url(request, size='medium'):
247247

248248
# Checks whether users are allowed to see the media file before giving them
249249
# the url
250-
xform = attachment.instance.xform
250+
xform = attachment.xform
251251

252252
helper_auth_helper(request)
253253

kobo/apps/openrosa/libs/serializers/attachment_serializer.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ class AttachmentSerializer(serializers.ModelSerializer):
4040
small_download_url = serializers.SerializerMethodField()
4141
medium_download_url = serializers.SerializerMethodField()
4242
large_download_url = serializers.SerializerMethodField()
43-
xform = serializers.ReadOnlyField(source='instance.xform.pk')
43+
xform = serializers.ReadOnlyField(source='xform_id')
4444
instance = serializers.ReadOnlyField(source='instance.pk')
4545
filename = serializers.ReadOnlyField(source='media_file.name')
4646

0 commit comments

Comments
 (0)