qwerty
qwerty

Reputation: 33

Django. How to reduce the number of database hits?

Please tell me how can I reduce the number of requests, I will attach the code below:

models.py

class Post(models.Model):
    ....
    @property
    def views_count(self):
        return PostViews.objects.filter(post=self).count()

class PostViews(models.Model):
    IPAddres= models.GenericIPAddressField(default="111.222.333")
    post = models.ForeignKey(Post, on_delete=models.CASCADE,related_name="post_views_count",)
    date = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.IPAddres

views.py

posts = Post.objects.filter(is_toplevel=True, status=Post.ACTIVE).select_related('author').prefetch_related('tags').select_related('category')

html

{% for post in posts %}
    ....
    {{ post.views_count }}
{% endfor %}

Due to the postview call, the number of hits increases by 10 sql...

Upvotes: 2

Views: 88

Answers (1)

Lucas Grugru
Lucas Grugru

Reputation: 1869

You can use Django annotation:

queryset = Post.objects.filter(is_toplevel=True, status=Post.ACTIVE)
queryset = queryset.annotate(views_count=Count("post_views_count"))
queryset = queryset.select_related('author', 'category')
queryset = queryset.prefetch_related('tags')

And remove your Post property in models.py

Upvotes: 1

Related Questions