为什么 URL 在将外键字段添加到模型后不起作用?

Why is the URL not working after adding foreignkey field to model?

我正在创建一个博客应用程序并为其博客文章添加了一个类别。添加新类别时,可以毫无问题地完成。但问题是我找不到特定类别 ID 的帖子并收到类似

的错误

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

但在我将字段类别 charafield 更新为 forenkeyfied 之前,它没有任何问题。

这是我的代码:

class Post(models.Model):
    title = models.CharField(max_length=200)
    slug = models.SlugField(max_length=200, unique=True)
    author = models.ForeignKey(User, on_delete= models.CASCADE,related_name='blog_posts')
    updated_on = models.DateTimeField(auto_now= True)
    content = SummernoteTextField(blank=True, null=True)
    created_on = models.DateTimeField(auto_now_add=True)
    status = models.IntegerField(choices=STATUS, default=0)
    image = models.ImageField(upload_to='images',null=True, blank=True)
    category = models.ForeignKey('blog.category', on_delete=models.SET_NULL, null=True, blank=True)
    
 class category(models.Model):
    name = models.CharField(max_length=80)
    def __str__(self):
        return self.name

views.py

def CategoryView(request, cats):
    category_posts = Post.objects.filter(category=cats.replace('-', ' '))
    return render(request, 'categories.html', {'cats':cats.replace('-', ' '), 'category_posts':category_posts})

forms.py

class PostForm(forms.ModelForm):
    category = forms.ModelChoiceField(queryset=category.objects.all().order_by('name'))
    class Meta:
        model = Post
        fields = ('title', 'category','author', 'content', 'image','status')

你没有分享完整的回溯,但错误可能是由这一行引起的

Post.objects.filter(category=cats.replace('-', ' '))

您正在使用字符串过滤 category 外键,因此出现错误。

您的意图似乎是针对类别名称进行过滤:

Post.objects.filter(category__name=cats.replace('-', ' '))