Django 获取当前帖子';s类

Django 获取当前帖子';s类,django,Django,因此,正如标题所说,我需要获得当前帖子的类别,以便在“相关帖子”部分中使用它,更准确地说,在cat_posts=post.objects.filter(category=?) (不要介意comments变量,因为我从本文中删除了部分PostView) 这是我的密码 views.py def PostView(request, slug): template_name = 'post-page.html' post = get_object_or_404(Post, slug=slug) comm

因此,正如标题所说,我需要获得当前帖子的类别,以便在“相关帖子”部分中使用它,更准确地说,在
cat_posts=post.objects.filter(category=?)
(不要介意comments变量,因为我从本文中删除了部分PostView)

这是我的密码

views.py

def PostView(request, slug):
template_name = 'post-page.html'
post = get_object_or_404(Post, slug=slug)
comments = post.comments.filter(active=True)

cat_posts = Post.objects.filter(Category=Post.Category)
cat_posts = cat_posts.order_by('-Date')[:3}

return render(request, template_name, {'post': post,
                                       'cat_posts':cat_posts})
models.py

class Category(models.Model):
name = models.CharField(max_length=100)

def __str__(self):
    return str(self.name)



class Post(models.Model):
title = models.CharField(max_length=120)
Category = models.CharField(max_length=120, default='None')
Thumbnail = models.ImageField(null=True, blank=True, upload_to="images/")
Text = RichTextField(blank=False, null=True)
slug = models.SlugField(max_length=200, unique=True)
author = models.ForeignKey(User, on_delete=models.CASCADE)
Overview = models.CharField(max_length=400)
Date = models.DateTimeField(auto_now_add=True)
main_story = models.BooleanField(default=False)


def __str__(self):
    return str(self.title)

def get_absolute_url(self):
    # return reverse('about', args=(str(self.id)))
    return reverse('home')

您可以通过
post.Category
(因此是
post
*对象,而不是
post
类)来获得此信息:

def PostView(请求,slug):
模板名称='post page.html'
post=获取对象或404(post,slug=slug)
comments=post.comments.filter(active=True)
cat_posts=Post.objects.filter(
类别=职位类别
).order_by('-Date')[:3]
返回渲染(
要求
模板名称,
{'post':post'cat_posts':cat_posts}
)
但是,与使用
类别
相比,使用
字符域
更好:如果您以后更改类别名称,则您的帖子不再指向有效类别


注意:通常Django模型中字段的名称是用snake_大小写的,而不是PerlCase,因此它应该是:
category
,而不是
category


非常感谢。这很有效,我已经用Post类而不是Post对象尝试过了。至于将类别改为ForeignKey,我应该在“on_delete”中添加什么?@adelbouakaz:问题是,如果你删除了一个类别,帖子会发生什么情况。有关可能的场景,请参阅文档:好的,谢谢,我不知道是否存在SET_DEFAULT
def PostView(request, slug):
    template_name = 'post-page.html'
    post = get_object_or_404(Post, slug=slug)
    comments = post.comments.filter(active=True)
    cat_posts = Post.objects.filter(
        Category=post.Category
    ).order_by('-Date')[:3]
    return render(
        request,
        template_name,
        {'post': post, 'cat_posts':cat_posts}
    )