Django / ListView / Use get_context_data to count all keys in a json variable

I would like to return in my Link.html the number of links contain in allLinks variable (json) So far I guess I misunderstand the use of get_context_data and how to pass to context['CountLink'] the total count of links.

With the current code , I got :

Liste des recherches

terre : <QuerySet [<Post: terre>, <Post: océan>]> Links
océan : <QuerySet [<Post: terre>, <Post: océan>]> Links

Models.py

class Post(models.Model):
    title = models.CharField(max_length=255)
    url = models.URLField(max_length=255)
    allLinks = models.JSONField()

    def __str__(self):
        return self.title

views.py

class LinkView(ListView): model = Post template_name = 'link.html'

def get_context_data(self, **kwargs):
    context = super().get_context_data(**kwargs)
    context['CountLink'] = Post.objects.all()
    return context

Link.html

  {% for post in object_list %}
  <li>
    <a href="{% url 'DetailLink' post.pk %}">{{ post.title }}</a> :
    {{CountLink}} Links
  </li>
  {% endfor %}

You can use count() In your case I think you want something like that, it will return count of Post model objects

context['CountLink'] = Post.objects.all().count()

For more info check this

Use the built-in length template filter:

{{ post.allLinks|length }} Links
Back to Top