I have created a database using Django. I have a small statistics page as shown below. Can I improve this code?
View file
def statistics(request):
""" Return the number of categories (Category is based on first
three-letter character, say Cry in the example) in the database
and its corresponding count.
The holotype is a protein name that ends in 1. Example: Cry1Aa1
A holotype is a single protein name used to name the lower rank based on identity.
Cry1Aa2 is named based on the identity to Cry1Aa1
"""
category_count = {}
category_holotype_count = {}
category_prefixes = []
total_holotype = 0
categories = \
PesticidalProteinDatabase.objects.order_by(
'name').values_list('name', flat=True).distinct()
for category in categories:
cat = category[:3]
if category[-1] == '1' and not category[-2].isdigit():
total_holotype += 1
count = category_holotype_count.get(cat, 0)
count += 1
category_holotype_count[cat] = count
category_count['Holotype'] = [total_holotype] * 2
for category in categories:
prefix = category[0:3]
if prefix not in category_prefixes:
category_prefixes.append(prefix)
for category in category_prefixes:
count = PesticidalProteinDatabase.objects.filter(
name__istartswith=category).count()
category_count[category] = [
count, category_holotype_count.get(category, 0)]
prefix_count_dictionary = {}
for prefix in category_prefixes:
prefix_count_dictionary[prefix] = category_count[prefix][0]
prefix_count_dictionary.pop('Holotype', None)
context = \
{'category_prefixes': category_prefixes,
'category_count': category_count}
return render(request, 'database/statistics.html', context)
Urls file
path('statistics/', views.statistics,
name='statistics'),
Sample HTML file
<b>General Statistics</b>
<table class="table table-bordered table-hover">
<thead>
<tr>
<th>No</th>
<th>Category</th>
<th>Total Count</th>
<th>Holotype Count</th>
</tr>
{% for key,value in category_count.items %}
<tr>
<td> {{ forloop.counter }} </td>
<td> {{ key }} </td>
<td> {{ value.0 }} </td>
<td> {{ value.1 }} </td>
</tr>
{% endfor %}
<thead>
<table>
request
. \$\endgroup\$