Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Django Rest How to show all related foreignkey object?

I have an blog website and my visitors can also comment on my blog posts. Each blog post have multiple comment and I want to show those comment under my each single blog post. Assume Blog1 have 10 comment so all 10 comment will be show under Blog1

here is my code:

models.py

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

class Blog(models.Model):
    blog_title = models.CharField(max_length=200, unique=True)

class Comment(models.Model):
  name = models.CharField(max_length=100)
  email = models.EmailField(max_length=100)
  comment = models.TextField()
  blog = models.ForeignKey(Blog, on_delete=models.CASCADE)

Serializer.py

class CommentSerializer(serializers.ModelSerializer):
      
      class Meta:
          model = Comment
          fields = '__all__' 


class BlogSerializer(serializers.ModelSerializer):  
    class Meta:
        model = Blog
        exclude = ("author", "blog_is_published")
        lookup_field = 'blog_slug'
        extra_kwargs = {
            'url': {'lookup_field': 'blog_slug'}
        }

views.py:

class BlogViewSet(viewsets.ModelViewSet):
    queryset = Blog.objects.all().order_by('-id')
    serializer_class = BlogSerializer
    pagination_class = BlogPagination
    lookup_field = 'blog_slug'

>Solution :

You can access comments list from blog object using comment_set attribute, so add comment_set field to your serializer:

class BlogSerializer(serializers.ModelSerializer):  
    comment_set = CommentSerializer(many=True)

    class Meta:
        model = Blog
        exclude = ("author", "blog_is_published")
        lookup_field = 'blog_slug'
        extra_kwargs = {
            'url': {'lookup_field': 'blog_slug'}
        }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading