我是Django的新手,并且构建了一个包含帖子的简单应用程序。我想在一页上显示与某些类别相关的帖子。我在网上做了很多研究,但似乎无法使它起作用。我认为问题出在我的views.py
我想CategoryListView中的get_queryset函数有问题。
'''
models.py
'''
from django.db import models
class Post(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
date = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)
category = models.ForeignKey(
'Category',
on_delete=models.SET_NULL,
null=True)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('post-detail', kwargs={'pk': self.pk})
class Category(models.Model):
name = models.CharField(max_length=100)
slug = models.SlugField(max_length=150, unique=True)
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('post-category', kwargs={'pk': self.pk})
'''
views.py
'''
from django.views.generic import ListView
from .models import Post, Category
class CategoryListView(ListView):
model = Post
template_name = 'posts/post_category.html'
def get_queryset(self):
category = get_object_or_404(Category, id=self.kwargs.get('category__name'))
return Posts.objects.filter(category_name=category)
'''
urls.py
'''
from .views import CategoryListView
urlpatterns = [
# urlpatterns for other pages left out for better readability
CategoryListView.as_view(), name='post-category')
]
该代码给我一个404,并且显示没有类别与我的查询匹配的消息。
答案 0 :(得分:0)
get_queryset
[Django-doc]函数应返回以下内容:
class CategoryListView(ListView):
# ...
def get_queryset(self):
return Post.objects.filter(category_id=self.kwargs.get('pk'))
此外,在您的网址中,您将需要使用带有pk
参数的模式,例如:
urlpatterns = [
path('category/<int:pk>', CategoryListView.as_view(), name='post-category')
]
话虽如此,如果您想显示有关类别的信息,将它设为DetailView
[Django-doc],然后反向查询该关系可能更有意义,例如:
class CategoryDetailView(DetailView):
model = Category
context_object_name = 'category'
template_name = 'posts/post_category.html'
在模板中,您可以使用以下方式呈现数据:
Category name: {{ category.name }}
{% for post in category.post_set.all %}
post: {{ post.title }}
{% endfor %}