Django模型类属性和实例属性?

时间:2016-09-05 02:38:51

标签: python django

我在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

创建PostHit个实例后,每次访问increase_hit()时都会调用DetailVie

但它并没有增加正确的方式。

首先它打印1.当我刷新页面时,它打印2.在下次刷新时,它再次打印2。它在2之后不再增加。

我的代码出了什么问题?我是否误解了类属性和实例属性?

1 个答案:

答案 0 :(得分:2)

您需要在更新后保存模型:

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

否则,您的更改仅在对象的生命周期内保持不变。