1👍
✅
Before I was using nested serializer but nested serializer slow down its response.
The nested serializer itself does not slow down the response, this simply because it will result in an N+1 problem: you need to load the related data in bulk.
You can use .prefetch_related(…)
[Django-doc] for this, so:
Section.objects.prefetch_related('sections')
This will load SubSection
s of the selected Section
(s) in bulk.
It however does not make much sense to use 'sections'
for the related_name=…
parameter [Django-doc], since this is the name of the relation in reverse. You thus might want to rename this to:
class SubSection(models.Model):
section = models.ForeignKey(
Section,
related_name='subsections',
on_delete=models.PROTECT
)
sub_title= models.TextField()
and thus prefetch with:
Section.objects.prefetch_related('subsections')
Source:stackexchange.com