我正在创建一个博客应用程序,并为其博客文章添加了一个类别。添加新类别时,可以毫无问题地完成。但问题是我找不到特定类别 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
View .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})
表单.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('-', ' '))
关于python - 为什么在模型中添加外键字段后 URL 不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68994255/