Django 如何获得整个查询集
我有一个模型叫PostForumDjango 如何获得整个查询集,django,django-templates,django-views,Django,Django Templates,Django Views,我有一个模型叫PostForum class PostForum(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone
class PostForum(models.Model):
category = models.ForeignKey(Category, on_delete=models.CASCADE)
title = models.CharField(max_length=100)
content = models.TextField()
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)
likes = models.ManyToManyField(User, related_name='forum_likes', blank=True)
在基于类的视图中,我有以下代码
class CategoryDetailView(DetailView):
model = Category
template_name = 'forum/forum_detail.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
category = get_object_or_404(Category, id=self.object.id)
posts = PostForum.objects.filter(category=category)
context['posts'] = posts,
return context
在模板中,我无法访问帖子标题或内容。我什么也没表现出来
{% for post in posts %}
{{post.title}}
<p>{{post.content}}</p>
{% endfor %}
{%for posts in posts%}
{{post.title}
{{post.content}
{%endfor%}
当我渲染{post}以查看整个查询集时
它表明
<QuerySet [<PostForum: My first post>]>
如何访问帖子的标题或内容您的
get\u context\u data
函数中有一个小错误,导致此问题。从上下文['posts']=posts,
行中删除尾随的,
,因此获取上下文数据应为:
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
category = get_object_or_404(Category, id=self.object.id)
posts = PostForum.objects.filter(category=category)
context['posts'] = posts # remove the trailing comma from this line
return context
无需更改模板
对于上下文,后面的逗号将context['posts']
转换为单个元素元组,其唯一元素是posts
queryset,即context['posts']=(posts,)
。因此,当您在模板中执行{%forpost-in-posts%}
时,您不是在查询集中的每个PostForm
上迭代,而是在元组中的每个元素上迭代。由于元组中只有一个元素,因此每次都会将整个posts
queryset绑定到post
循环变量,而不是将每个PostForum
实例绑定到post
python中的尾随逗号!同意!正如所期望的那样,t=(1)
是一个单元素元组;)