Home > Software engineering >  Django Rest Framework return one model inside another model's detail view
Django Rest Framework return one model inside another model's detail view

Time:03-27

Trying to build a forum clone. There are a list of boards. Each board contains a list of threads. Each thread contains a list of posts. I'm confused about some things.

  1. Is the BoardDetail view returning a list of threads the correct approach?
  2. I'm not sure how that can be achieved.

Here is my attempt.

views.py

class BoardDetail(generics.ListAPIView):
    # what needs to be done here to return the threads belonging to a particular board?
    queryset = Thread.objects.filter()  
    serializer_class = ThreadSerializer

models.py

class Board(models.Model):

    name = models.CharField(max_length=25, primary_key=True)
    created = models.DateTimeField(auto_now_add=True)
    board_admin = models.ForeignKey('auth.User', on_delete=models.CASCADE, related_name='board_admin')
    board_moderator = models.ManyToManyField(User, related_name='board_moderator')

    class Meta:
        ordering = ['created']


class Thread(models.Model):

    title = models.CharField(max_length=250)
    created = models.DateTimeField(auto_now_add=True)
    thread_admin = models.ForeignKey('auth.User', on_delete=models.CASCADE, related_name='thread')
    board_id = models.ForeignKey(Board, on_delete=models.CASCADE, related_name="thread")

    class Meta:
        ordering = ['created']

CodePudding user response:

you can do this by using nested serializers, this is a simple example of how to do these nested serializers.

In Board model, parent model, add this function to fetch all threads related to a certain object by foreign key or id.

@property
def threads(self):
    return self.thread_set.all() # thread is the name of the child class

Then in your serializer class for Board, the parent class add a field to contain threads with the parent id, it must have the same name as of the property we just created in the Board model, parent model, and assigned the serializer of the Threads model serializer, child model

threads = ThreadsSerializer(many=True, required=False)

Then, u must add threads in the fields for the Board serializer, parent model

fields = ('name','created','board_admin','board_moderator','threads')

this should allow you display all the threads related to a board.

  • Related