Home > OS >  Django. How to reduce the number of database hits?
Django. How to reduce the number of database hits?

Time:10-24

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...

CodePudding user response:

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')
queryset = queryset.select_related('category')
queryset = queryset.prefetch_related('tags')

And remove you Post property in models.py

  • Related