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'