Shankar Ghimire
Shankar Ghimire

Reputation: 146

How to get data from another class with ForeignKey relationship

I have two class in my Model.py one is Blog class and another is comment class. i want to get comment of related blog class

i mean if comment_1 has ForeignKey of blog_1 then while retrieving blog_1 i want to get comment also at the same time

models.py


class Blog(models.Model):
    title = models.CharField(max_length=200)
    content = models.TextField()
    image = models.CharField(max_length=200)
    created_at = models.DateTimeField(timezone.now())
    views = models.IntegerField(null=True, blank=True)

    def __str__(self):
        return self.title


class comment(models.Model):
    blog = models.ForeignKey(Blog, on_delete=models.CASCADE)
    name = models.CharField(max_length=50)
    email = models.EmailField(max_length=100)
    comment = models.TextField()
    image = models.CharField(max_length=200,
                             null=True, blank=True)
    commented_at = models.DateTimeField(timezone.now())

    def __str__(self):
        return self.blog.title

Serializers.py

class CommentSerializer(serializers.ModelSerializer):
    # blog = BlogSerializer()

    class Meta:
        model = comment
        fields = '__all__'


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

    class Meta:
        model = Blog
        fields = ['id', 'title', 'content', 'image', 'created_at', 'comment']

views.py

class BlogViewSet(viewsets.ModelViewSet):
    queryset = Blog.objects.all()
    serializer_class = BlogSerializer
    pagination_class = MyLimitOffSetPaginations
    filter_backends = [SearchFilter]
    search_fields = ['title', 'content']

I have try in this way but i am getting error the error is saying that Blog object has no attribute comment

but i want to get comment of related blog

please any one can help me to get blog with comment that has ForeignKey of blog

Upvotes: 1

Views: 87

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476574

The default value for the related_name=… parameter [Django-doc] is modelname_set, so since you did not specify a related_name, the name of the manager to obtain the Comments for a given Blog is comment_set:

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

    class Meta:
        model = Blog
        fields = ['id', 'title', 'content', 'image', 'created_at', 'comment_set']

You can however change the name of the reverse relation with:

class Comment(models.Model):
    blog = models.ForeignKey(
        Blog,
        on_delete=models.CASCADE,
        related_name='comments'
    )
    # …

and then thus use comments instead.

Upvotes: 2

Related Questions