【问题标题】:Why is the URL not working after adding foreignkey field to model?为什么将外键字段添加到模型后 URL 不起作用?
【发布时间】:2021-10-29 19:18:28
【问题描述】:

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

字段 'id' 需要一个数字,但得到的是 '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')

【问题讨论】:

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


    【解决方案1】:

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

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

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

    您的意图似乎是过滤类别名称:

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

    【讨论】:

      猜你喜欢
      • 2019-12-15
      • 1970-01-01
      • 1970-01-01
      • 2019-05-26
      • 1970-01-01
      • 2022-11-23
      • 2014-12-07
      • 2019-11-23
      • 2020-02-20
      相关资源
      最近更新 更多