jsondjangodjango-templatesdjango-template-filtersdjango-jsonfield

Django ListView count all keys in a JSON variable


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

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 %}

Example of allLinks: {"0": "github.com/kubernetes/kubernetes/releases/tag/v1.26.0", "1": "kubernetes.io/docs/concepts/overview/what-is-kubernetes",}


Solution

  • Use the built-in length template filter:

    {{ post.allLinks|length }} Links