A problem about get_absolute_url()

16 views
Skip to first unread message

ozgur yilmaz

unread,
Nov 12, 2012, 10:06:54 AM11/12/12
to django...@googlegroups.com
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)

Bill Freeman

unread,
Nov 12, 2012, 12:43:55 PM11/12/12
to django...@googlegroups.com

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
      
Reply all
Reply to author
Forward
0 new messages