Leon
Leon

Reputation: 6554

id of the another class in Django

I have 2 models:

class Producer(models.Model):
    def __unicode__(self):
            return self.name
    def get_absolute_url(self):
        return "/prod/%i/" % self.id 
    name = models.CharField(max_length=10, unique=True)

class Car(models.Model):
    def __unicode__(self):
            return self.name
    def get_absolute_url(self):
        return "/prod/%s/car/%i" % Producer.id, self.id 
    name = models.CharField(max_length=10, unique=True)
    prod = models.ForeignKey(Producer)

On /sitemap.xml I have an error: type object 'Producer' has no attribute 'id'. How to get in the method get_absolute_url (of Car class) id of the Producer? Thanks. I try Producer_id, Producer__id but it doesn't works.

Upvotes: 0

Views: 49

Answers (1)

Aamir Rind
Aamir Rind

Reputation: 39709

It should be:

def get_absolute_url(self):
    return "/prod/%s/car/%s" % (self.prod.id, self.id)

Also looking into your code there can be done two more improvements:

  1. Model class method should come after the fields
  2. You should use reverse-resolution-of-urls instead of hard coding the url /prod/%s/car/%s which is a bad way to do.

Upvotes: 1

Related Questions