Django models class attribute and instance property?
<p>I implement very simple hit-count models in <code>Django</code>.</p>

<p><code>models.py</code></p>

<pre><code>from django.db import models

from model_utils.models import TimeStampedModel

from posts.models import Post


class PostHit(TimeStampedModel):
    post = models.ForeignKey(Post, related_name='post_hits')
    num_of_hit = models.IntegerField()

    class Meta:
        verbose_name_plural = "Post hits"

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

    def increase_hit(self):
        self.num_of_hit += 1
</code></pre>

<p><code>views.py</code></p>

<pre><code>from django.views.generic.detail import DetailView
from django.core.exceptions import ObjectDoesNotExist

from posts.models import Post, PostHit
from posts.forms import CommentForm


class PostDetailView(DetailView):
    model = Post

    def get_context_data(self, *args, **kwargs):
        context = super().get_context_data(**kwargs)
        context['category'] = self.kwargs['category']
        context['form'] = CommentForm()
        context['tracking_hit_post'] = self.tracking_hit_post()
        return context

    def tracking_hit_post(self):
        post = self.model.objects.get(pk=self.object.id)
        post_hit = PostHit.objects.filter(post=post).first()
        if post_hit:
            post_hit.increase_hit()
        else:
            post_hit = PostHit.objects.create(
                post=post,
                num_of_hit=1
            )
        print(post_hit.num_of_hit)
        return post_hit.num_of_hit
</code></pre>

<p>Once <code>PostHit</code> instance created, it calls <code>increase_hit()</code> everytime I visit <code>DetailVie</code>.</p>

<p>But it doesn't increase right way. </p>

<p>First it prints 1. And when I refresh the page, it prints 2. At next refresh, it prints 2 again. It doesn't increase anymore after 2. </p>

<p>What's wrong with my code? Did I misunderstand class attribute and instance property?</p>

<p>You need to save the model after updating it:</p>

<pre><code>def increase_hit(self):
    self.num_of_hit += 1
    self.save()
</code></pre>

<p>Otherwise, your changes persist only for the lifetime of the object.</p>

python django