Home > Mobile >  Retrieve data from models having reverse relationship in django rest
Retrieve data from models having reverse relationship in django rest

Time:05-29

I have 3 models where model A has foreign key of another in reverse order like:-

class Book(models.Model):
name = models.CharField(max_length=100)
img=models.CharField(blank=True)
category=models.CharField(max_length=100,null=True)

class Section(models.Model):
book= models.ForeignKey(Book, related_name='sections', on_delete=models.PROTECT)
title= models.TextField(null=True)

class SubSection(models.Model):
section=models.ForeignKey(Section, related_name='subSections', 
                           on_delete=models.PROTECT, null=True) 
sub_title= models.TextField(null=True) 

I am trying to fetch all sections and subsections on the basis of book id. Before I was using nested serializer but nested serializer slow down its response. i am trying to achieve it with select_related can anyone help me with view query and serializer class. I want response like:

data=[ "section": "A", "title": "intro", "subsection": [ { "id": 1, "sub_title": "title" } ] ]

CodePudding user response:

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 SubSections 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')
  • Related