【问题标题】:Django get_query_set ValueErrorDjango get_query_set ValueError
【发布时间】:2020-12-10 22:13:34
【问题描述】:

我正在尝试在 django 中为帖子类别创建一个 ListView。因此,对于每个帖子,我都包含一个链接,该链接会将您发送到包含所有具有相同类别的帖子的页面。我在我的 PostCategoryListView 上使用 get_queryset 来过滤它们,但它显示了错误

Field 'id' expected a number but got 'technology'

我的模型:

from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone

class Category(models.Model):
    type = models.CharField(max_length = 20)
    image = models.ImageField(default = 'default.jpg', upload_to = 'category_pics')

    def __str__(self):
        return self.type


class Post(models.Model):
    title = models.CharField(max_length = 30)
    content = models.TextField()
    date_posted = models.DateTimeField(default = timezone.now)
    author = models.ForeignKey(User, on_delete = models.CASCADE)
    category = models.ForeignKey(Category, on_delete = models.CASCADE)


    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse('post-detail', kwargs={'pk': self.pk}) 

我的views.py:

class PostCategoryListView(ListView):
model = Post
template_name = 'blog/category_posts.html'
context_object_name = 'posts'

def get_queryset(self):
    kategoria = get_object_or_404(Post , category = self.kwargs.get('category'))
    return Post.objects.filter(category = kategoria)

我在 htmt 中的锚标记:

<a href="{% url 'post-category' post.category %}"><h2>{{ post.category }}</h2></a>

我的 urls.py:

urlpatterns = [
path('admin/', admin.site.urls),
path('', PostListView.as_view() , name='blog-home'),
path('post/<str:username>/', UserPostListView.as_view(), name = 'user-posts'),
path('post/<int:pk>/', PostDetailView.as_view(), name = 'post-detail'),
path('post/new/', PostCreateView.as_view(), name = 'post-new'),
path('post/<int:pk>/delete/', PostDeleteView.as_view(), name = 'user-posts'),
path('category/<str:category>/', PostCategoryListView.as_view(), name = 'post-category')

]

谁能帮我理解出了什么问题?因此,在最后一条路径中,我想使用 url 中传递的属性来按类别过滤我的帖子

【问题讨论】:

    标签: python html django url


    【解决方案1】:

    您要先查找类别,然后过滤该类别的帖子。您的代码正在做的是使用类别名称查找帖子,然后使用该帖子作为类别过滤器......这没有任何意义。 :)

    你想做的是:

    def get_queryset(self):
        kategoria = get_object_or_404(Category, type=self.kwargs.get('category'))
        return Post.objects.filter(category=kategoria)
    

    【讨论】:

      猜你喜欢
      • 2011-05-08
      • 2017-12-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-17
      • 2015-05-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多