Home > OS >  Django Rest How to show all related foreignkey object?
Django Rest How to show all related foreignkey object?

Time:11-27

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

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'

CodePudding user response:

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'}
        }
  • Related