【问题标题】:'HitCountDetailView' object has no attribute 'category'“HitCountDetailView”对象没有“类别”属性
【发布时间】:2021-08-26 21:30:44
【问题描述】:

我正在尝试向我的 DetailView 添加用于过滤的额外上下文。抛出视图对象没有属性类别的错误

型号

class Post(models.Model):
    title = models.CharField(max_length=200)
category = models.ForeignKey('Category', on_delete=models.SET_NULL, null=True, blank=True)
    slug = models.SlugField(max_length=100, unique=True, editable=True)

view.py

class HitCountDetailView(HitCountDetailView):
    model = Post
    template_name = 'detail.html'
    context_object_name = 'post'
    slug_field = 'slug'
    count_hit = True

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['similar_posts'] = Post.objects.filter(category=self.category).exclude(slug=self.slug)
        return context


**urls.py**


```python
    path('detail/<slug>/', HitCountDetailView.as_view(), name='post-detail')

【问题讨论】:

    标签: django django-models django-rest-framework django-views


    【解决方案1】:

    您应该使用self.object.category而不是self.categoryself.object.slug而不是self.slug进行过滤。因此,您可以通过以下方式实现:

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['similar_posts'] = Post.objects.filter(
            category=self.object.category
        ).exclude(pk=self.object.pk)
        return context

    您可以通过查询对象本身而不是其类别来优化效率:

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['similar_posts'] = Post.objects.filter(
            category__post=self.object
        ).exclude(pk=self.object.pk)
        return context

    【讨论】:

    • 谢谢。很高兴你能帮上忙
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-03
    • 2020-09-06
    • 1970-01-01
    • 2020-02-25
    • 1970-01-01
    相关资源
    最近更新 更多