简体   繁体   English

如何获得对 Django 中特定博客文章的评论?

[英]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."我得到的错误 - “ValueError:精确查找的 QuerySet 值必须限制为使用切片的一个结果。”

objects.filter() returns a queryset . objects.filter () 返回一个查询集。 The filter method is expecting an instance of BlogPost (to get the id) or a integer-id since objects.filter(post= pk ) filter 方法需要一个 BlogPost 实例(获取 id)或一个整数 id,因为 objects.filter(post= pk )

Use objects.get(), that way you get a instance of BlogPost, not a queryset:使用 objects.get(),这样你得到一个 BlogPost 的实例,而不是一个查询集:

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:其中之一是返回 Http404,这是最简单的方法:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM