Saptorshe Das
Saptorshe Das

Reputation: 19

How to get comment for the particular Blog Post in Django?

#Models.py
#BlogPost Model
class BlogPost(models.Model):
    POST_CATEGORY = (
        ('Education','Education'),
        ('Tech','Tech'),
        ('Automobile','Automobile'),
        ('Other','Other')
    )
    title = models.CharField(max_length=150)
    thumbnail = models.ImageField(upload_to='Blog Thumbnail')
    category = models.CharField(max_length=100, choices = POST_CATEGORY )
    content = models.TextField()
    timestamp = models.DateTimeField(auto_now_add=True)
    slug = models.CharField(max_length=200, unique=True, null=True)
    tags = models.CharField(max_length=150, null=True, blank=True)
    writer = models.ForeignKey(User,on_delete=models.CASCADE,null=False)

    def __str__(self):
        return self.title

#BlogComment Model
class BlogComment(models.Model):
    post = models.ForeignKey(BlogPost,on_delete=models.CASCADE)
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    comment = models.TextField()
    parent = models.ForeignKey('self',on_delete=models.CASCADE,null=True)
    timestamp = models.DateTimeField(auto_now_add=True)


#Views Code
def blogPost(request, slug):
    post = BlogPost.objects.filter(slug=slug)
    '''How to get comment for particularly this post'''
    comments = BlogComment.objects.filter(post=post)  # It is giving a wrong answer
    '''The error I am getting 
       ValueError: The QuerySet value for an exact lookup must be limited to one result using slicing.'''
    print(comments)
    context = {
        'Post':post,
        'Comments':comments
    }
    return render(request,'blogpost.html',context)

How to get the comment for the particulary for this blog post? The error I am getting -" ValueError: The QuerySet value for an exact lookup must be limited to one result using slicing."

Upvotes: 0

Views: 444

Answers (1)

Yasser Mohsen
Yasser Mohsen

Reputation: 1480

objects.filter() returns a queryset. The filter method is expecting an instance of BlogPost (to get the id) or a integer-id since objects.filter(post=pk)

Use objects.get(), that way you get a instance of BlogPost, not a queryset:

post = BlogPost.objects.get(slug=slug)
comments = BlogComment.objects.filter(post=post)

Additions:

You can also handle the exception that could happen if the post does not exist by different ways. One of them is returning Http404, and here is the easiest way to do that:

from django.shortcuts import get_object_or_404
post = BlogPost.objects.get_object_or_404(slug=slug)

Upvotes: 2

Related Questions