I want to fill the array ‘v’ with the number of doctors in each department, I got this error :
v[i]=Doctor.objects.all().filter(idDept__deptName__contains=s.deptName).count()
~^^^
IndexError: list assignment index out of range
views.py
def accueilAdmin(request):
if not request.user.is_staff:
return redirect('loginAdmin')
depts=Department.objects.all()
v=[]
i=1
for s in depts:
v[i]=Doctor.objects.all().filter(idDept__deptName__contains=s.deptName).count()
i+=1
models.py
class Department(models.Model):
deptName = models.CharField(max_length=50, null=False)
...
return self.deptName
class Doctor(models.Model):
name= models.CharField(max_length=50)
...
idDept = models.ForeignKey(Department, on_delete=models.CASCADE, null=True)
def __str__(self):
return self.name
I don’t know how to solve it, I would appreciate your help, thank you.
>Solution :
Indexes start at 0, you can append to the list with:
def accueilAdmin(request):
if not request.user.is_staff:
return redirect('loginAdmin')
depts = Department.objects.all()
v = []
for s in depts:
v.append(
Doctor.objects.all()
.filter(idDept__deptName__contains=s.deptName)
.count()
)
i += 1
But this is likely all not necessary and inefficent, you can just annotate your Departments with the number of Doctors:
from django.contrib.auth.decorators import user_passes_test
from django.db.models import Count
from django.urls import reverse_lazy
@user_passes_test(lambda u: u.is_staff, 'loginAdmin')
def accueil_admin(request):
depts = Department.objects.annotate(num_doctors=Count('doctor'))
# …
The Department objects in depts will then have an extra attribute .num_doctors with the number of related Doctors. This is done in the same query, hence it reduces the amount of queries enormously:
Note: Functions are normally written in snake_case, not PascalCase, therefore it is
advisable to rename your function toaccueil_admin, not.accueilAdmin