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'))
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>
- [Django]-Django tables 2: Hyperlinking items in a column
- [Django]-What should be the default value for a not Null Unique field
- [Django]-I keep getting the following error "local variable 'total_results' referenced before assignment"
Source:stackexchange.com