[Django]-Django query annotate values get list from reverse foreign key

4👍

If you are using a postgres as a database, then you can use an ArrayAgg function:

from django.contrib.postgres.aggregates import ArrayAgg

authors = Author.objects.annotate(blogs=ArrayAgg('blog_set__title'))
👤Ersain

1👍

You can query with:

authors = Author.objects.prefetch_related('blog_set')

Then in the template, you can render with:

<ul>
  {% for author in authors %}
    <li>{{ author }}</li>
    <ul>
      {% for blog in author.blog_set.all %}
        <li>{{ blog }}</li>
      {% endfor %}
    </ul>
  {% endfor %}
</ul>

Leave a comment