def send_template(request):
my_folders = Folders.objects.filter(parent=None).order_by('name')
new_headers = {}
for foldr in my_folders:
en_count = FolderEntries.objects.filter(folder = foldr.id ).count()
new_headers[foldr.id] = en_count
return render(request, 'folders.html', 'new_headers':new_headers)
new_headers contains data in such way:- {190: 1, 196: 0, 199: 0, 121: 0, 185: 1, 194: 1, 108: 3, 168: 4, 197: 0, 195: 0, 198: 0, 171: 1}
Now i want to get new_headers in html template using indexing For example:- new_headers[190]
How to do this..Anyone plz help
i am sending this data to my html template:- {190: 1, 196: 0, 199: 0, 121: 0, 185: 1, 194: 1, 108: 3, 168: 4, 197: 0, 195: 0, 198: 0, 171: 1}
Now i want to do indexing in this data.
CodePudding user response:
Indexing is deliberately not supported in the Django template language, because it is writing business logic in the template. For a fixed key, you can use new_headers.190
, you can also register a custom lookup, but usually that means that the logic is not effective.
You can .annotate(…)
[Django-doc] with:
from django.db.models import Count
def send_template(request):
my_folders = (
Folders.objects.filter(parent=None)
.order_by('name')
.annotate(num_entries=Count('folderentries'))
)
return render(request, 'folders.html', {'new_headers': new_headers})
The Folders
objects that arise from this QuerySet
will have an extra attribute .num_entries
.