Django Field 'id' 需要一个数字但得到了 'coding'

Django Field 'id' expected a number but got 'coding'

我在尝试显示与某一类别相关的所有帖子时遇到错误。 错误消息:字段 'id' 需要一个数字但得到了 'coding'

查看代码:

def CategoryView(request, cats):
    category_posts = Item.objects.filter(item_category=cats)
    return render(request, 'waqart/categories.html', {'cats':cats, 'category_posts':category_posts })

URL:

路径('category/str:cats/',分类视图,名称='category'),

模板文件:

{%extends 'waqart/base.html' %}
{% block content %}
<h1>{{cats}}</h1> 
<div class="flex flex-wrap">
{% for item in category_posts %}

  <h2 class="text-gray-900 text-xl title-font font-medium"{{item.title|truncatechars:40}}</h2>

{% endfor %}

</div>

{% endblock content %}

型号:

class Categories(models.Model):
    name = models.CharField(max_length=200)
    summary = models.CharField(max_length=200)
    slug = models.CharField(max_length=200)

    class Meta:
        verbose_name_plural = 'Categories'

    def __str__(self):
        

        return self.name



class Item(models.Model):
    title = models.CharField(max_length=100)
    description= RichTextField(blank=True, null=True)
    main_image= models.ImageField(null=True, blank=True,upload_to='images/')
    date = models.DateTimeField(auto_now_add=True)
    item_slug = models.CharField(max_length=200, default=1)
    item_category = models.ForeignKey(Categories, default='Coding', on_delete=SET_DEFAULT)

如果你过滤 ForeignKey,那么 Django 将过滤目标对象的 primary 键,通常是 AutoField,除非您引用另一个(唯一)列,或将另一个主键定义为字段。

您可能想要过滤类别的 slug

def CategoryView(request, cats):
    category_posts = Item.objects.filter(<strong>item_category__slug=cats</strong>)
    return render(
        request,
        'waqart/categories.html',
        {'cats':cats, 'category_posts':category_posts }
    )

如果您还需要获取类别,我们可以在两个查询中执行此操作:

from django.shortcuts import get_object_or_404

def CategoryView(request, cats):
    category = <strong>get_object_or_404(</strong>Category, slug=cats<strong>)</strong>
    category_posts = Item.objects.filter(<strong>item_category=category</strong>)
    return render(
        request,
        'waqart/categories.html',
        {'category': category, 'category_posts':category_posts }
    )