tuna
tuna

Reputation: 6351

Django - List index out of range

I have a ManyToManyField in my model. I need to get the third item for every query as below.

class Staff(models.Model):
    status = models.BooleanField(default=True)
    person = models.ForeignKey(Person)
    staff_job_categories = models.ManyToManyField(StaffJobCategory)
    staff_titles = models.ManyToManyField(PersonTitle, null=True, blank=True)

    def get_job_categories(self):
          return self.staff_job_categories.all()[3]

I use the get_job_categories function for admin list_filter but I want to show only the 3rd item in every many to many array.

But get the List index out of range ERROR; by the way;

def get_job_categories(self):
    return self.staff_job_categories.all()[:3]

Works fine. but gets all the objects till i get what i want.

Upvotes: 0

Views: 5756

Answers (2)

Weeble
Weeble

Reputation: 17890

The first item in a sequence has index 0. The third item has index 2. Perhaps that's your only problem?

E.g. try:

def get_job_categories(self):
    return self.staff_job_categories.all()[2]

However, this assumes that you know for certain that all staff have at least three job categories and that their order is predictable. Is that actually the case? I don't think Django's ManyToManyField gives you any guarantee about the order that the related objects will be returned.

Upvotes: 0

dani herrera
dani herrera

Reputation: 51655

This should work for jobs binded to less than 3 categories:

return ( self.staff_job_categories.all()[2] 
         if self.staff_job_categories.count() >= 3 
         else None
       )

Or:

return ( self.staff_job_categories.all()[2] 
         if len( self.staff_job_categories.all()[:3] ) >= 3 
         else None
       )

To avoid all categories recount.

Upvotes: 3

Related Questions