Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

IndexError: list assignment index out of range (filling an array in a for loop with count() of objects)

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 to accueil_admin, not accueilAdmin.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading