i want to print number of views for a specific post for e.g barack obama = 3 albert einstein = 1 elon musk = 0 that's it, but it print multiple values for each entries as you can see in the image. so how to achieve this. should i have to use dictionary or what ? enter image description here
models.py
class ObjectViewed(models.Model):
user = models.ForeignKey(User, blank=True, null=True, on_delete=models.CASCADE)
ip_address = models.CharField(max_length=220, blank=True, null=True)
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) # User, Blog, or any other models
object_id = models.PositiveIntegerField() # User id, Blog id, or any other models id
content_object = GenericForeignKey('content_type', 'object_id')
timestamp = models.DateTimeField(auto_now_add=True)
views.py
class PostListView(ListView):
model = Post
template_name = 'edmin/post/postList.html'
context_object_name = 'posts'
ordering_by = ['-created']
def get_queryset(self):
post=Post.objects.filter(author=self.request.user)
return post
def get_context_data(self, *args, **kwargs):
context = super().get_context_data(*args, **kwargs)
post=Post.objects.filter(author=self.request.user)
c_type = ContentType.objects.get_for_model(Post)
context['count_view'] = [ObjectViewed.objects.filter(content_type=c_type, object_id=p.id) for p in post ]
print(context['count_view'])
return context
postList.html
<table id="table_id" class="table display" border='2' align="center">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Title</th>
<th scope="col">Banner Title</th>
<th scope="col">Created</th>
<th scope="col">Number of Views</th>
<th scope="col">Status</th>
<th scope="col">Edit</th>
<th scope="col">Delete</th>
</tr>
</thead>
<tbody style="color:#000">
{% for post in posts %}
{% if post.status == 'Draft' %}
{% else %}
<tr>
<th scope="row">{{ forloop.counter }}</th>
<td><a style="color:blue" href="{% url 'edmin:post_detail_view' pk=post.pk %}">{{ post.title }}</a></td>
<td>{{ post.banner_title }}</td>
<td>{{ post.created }}</td>
<td>
{% for c in count_view %}
{{ c|length }}
{% endfor %}
</td>
<td>{{ post.status }}</td>
<td><a href="{% url 'edmin:post_update_view' pk=post.pk %}" class="btn btn-outline-dark btn-sm">Edit</a></td>
<td><a href="" class="btn btn-outline-danger btn-sm">Delete</a></td>
</tr>
{% endif %}
{% endfor %}
</tbody>
</table>