pythondjangoclassdjango-views

django get_object() getting called many times


I have a model- Article, and this code snippet

class ArticleDetailView(HitCountDetailView):
    model = Article
    # some code...
    
    def get_object(self):
        article = super(ArticleDetailView, self).get_object()
        slug = self.kwargs['slug']
        article = get_object_or_404(Article, slug=slug)
        
        print(article.some_count.counts)
        
        return article

this code is line printing the value of article.some_count_counts 3 times, it means the function get_object() is getting called 3 times.

But why so? that's my question.


Solution

  • Just remove the get_object() method.

    Django DetailView itself can get objects with slug field.
    So calling that function again is redundant.

    supporting doc:
    https://docs.djangoproject.com/en/5.2/ref/class-based-views/mixins-single-object/#django.views.generic.detail.SingleObjectMixin.slug_url_kwarg