On Mon, Nov 12, 2012 at 10:06 AM, ozgur yilmaz <yelb...@gmail.com> wrote:
> Hi all, > > I have 4 classes and i want to build a get_absolute_url() for a class, > querying other 3 classes. But i get "list index out of range" error > for the FILTER row. Any ideas? > > class Aaa( models.Model ): > ... > ... > > class City( models.Model ): > ... > ... > > class Bbb( models.Model ): > aaa = models.ForeignKey( Aaa ) > city = models.ForeignKey( City ) > ... > ... > > class Ccc( models.Model ): > aaa = models.ForeignKey( Aaa ) > ... > ... > > def get_absolute_url(self): > > bbbs = Bbb.objects.filter( aaa = self.aaa ) > > city = City.objects.get( id = bbbs[0].city.id ) > > return "/" + city.name + "/" + str(self.id) > There may be something else too, but I think that you want get "bbbs" as follows: bbbs = self.aaa.bbb_set.all() And you will need to check that bbbs is not empty before applying "[0]" to it. Also, once you have a bbb for sure, then get city by using city = bbbs[0].city In summary, something like: def get_absolute_url(self): if self.aaa.bbb_set.count() < 1: return 'some_fixed_url_for_when_a_Ccc_has_no_bbbs' # Or raise a 404 or whatever return '/%s/%d' % (self.aaa.bbb_set.all()[0].city.name, self.id) Bill -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-users@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.