user3595632 user3595632 - 3 months ago 31
Python Question

Django models class attribute and instance property?

I implement very simple hit-count models in

Django
.

models.py


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


views.py


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


Once
PostHit
instance created, it calls
increase_hit()
everytime I visit
DetailVie
.

But it doesn't increase right way.

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.

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

Answer

You need to save the model after updating it:

def increase_hit(self):
    self.num_of_hit += 1
    self.save()

Otherwise, your changes persist only for the lifetime of the object.