Skip to content

Commit 87529d1

Browse files
authored
Merge pull request #1273 from syucream/syucream/accelerate-entry-retrieve
Reduce N+1 on entry get APIv2
2 parents f82109d + 8a3fcf2 commit 87529d1

File tree

1 file changed

+11
-4
lines changed

1 file changed

+11
-4
lines changed

entry/api_v2/serializers.py

+11-4
Original file line numberDiff line numberDiff line change
@@ -532,7 +532,7 @@ class Meta:
532532
@extend_schema_field(serializers.ListField(child=EntryAttributeTypeSerializer()))
533533
def get_attrs(self, obj: Entry) -> list[EntryAttributeType]:
534534
def get_attr_value(attr: Attribute) -> EntryAttributeValue:
535-
attrv = attr.get_latest_value(is_readonly=True)
535+
attrv = attr.attrv_list[0] if len(attr.attrv_list) > 0 else None
536536

537537
if not attrv:
538538
return {}
@@ -560,7 +560,7 @@ def get_attr_value(attr: Attribute) -> EntryAttributeValue:
560560
"name": x.referral.entry.schema.name,
561561
},
562562
}
563-
for x in attrv.data_array.all()
563+
for x in attrv.data_array.all().select_related("referral")
564564
if x.referral and x.referral.is_active
565565
]
566566
}
@@ -580,7 +580,7 @@ def get_attr_value(attr: Attribute) -> EntryAttributeValue:
580580
if x.referral and x.referral.is_active
581581
else None,
582582
}
583-
for x in attrv.data_array.all()
583+
for x in attrv.data_array.all().select_related("referral")
584584
if not (x.referral and not x.referral.is_active)
585585
]
586586
return {"as_array_named_object": array_named_object}
@@ -721,9 +721,16 @@ def get_default_attr_value(type: int) -> EntryAttributeValue:
721721
case _:
722722
raise IncorrectTypeError(f"unexpected type: {type}")
723723

724+
attrv_prefetch = Prefetch(
725+
"values",
726+
queryset=AttributeValue.objects.filter(is_latest=True).select_related(
727+
"referral", "group", "role"
728+
),
729+
to_attr="attrv_list",
730+
)
724731
attr_prefetch = Prefetch(
725732
"attribute_set",
726-
queryset=Attribute.objects.filter(parent_entry=obj),
733+
queryset=Attribute.objects.filter(parent_entry=obj).prefetch_related(attrv_prefetch),
727734
to_attr="attr_list",
728735
)
729736
entity_attrs = (

0 commit comments

Comments
 (0)