python - 为什么在模型中添加外键字段后 URL 不起作用?

标签 python python-3.x django django-models django-queryset

我正在创建一个博客应用程序,并为其博客文章添加了一个类别。添加新类别时,可以毫无问题地完成。但问题是我找不到特定类别 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/

相关文章:

python - 命令帮助(通过 -h) 其中 `argparse` 是范围检查输入端口号

python - 两人骰子游戏的得分问题

python-3.x - AWS Lambda 到 Firestore 错误 : cannot import name 'cygrpc'

python - 如何在 Django 管理 View 中显示整个现有的 postgres 数据库

javascript - 如何自动将目标 ="_blank"添加到外部链接?

python - Python 中的规范 URL 比较?

python - 从列表中生成字典的最快方法,其中键 == 值

python - 如何删除列表中的整个字典?

python - 同步本地和 Elastic Beanstalk 数据库?

python - 在 python 中绘制 3d 数据的 2d 切片(最好使用 matplotlib)