Django how to get object in one query to database

models.py

class Post(models.Model):
    pass

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

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

views.py

def get_posts(request, topic=""):
    posts = Post.objects.filter(status=Post.OPEN).select_related('author').prefetch_related('tags').select_related('category').select_related('post_views_count')

posts.hml

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

Due to the call of views, the number of sql queries grows by 10 hits.How do I get this data in place with the data received by the model Post?

I suppose you have forgot the 'context' param to pass to the HTML file, that help the DTL (Django Template Language) to read the model. Here I write an example for you:

def get_posts(request, topic=""):
    posts = Post.objects.filter(status=Post.OPEN).select_related('author').prefetch_related('tags').select_related('category').select_related('post_views_count')
    context = {'post': Post.object.all()}
   return render(request,'file.html',context)

I hope I've solved your problem, if not, please contact me I will try to help you more, Your best.

Back to Top