Micah Pearce
Micah Pearce

Reputation: 1945

Django __str__ gives object has no attribute error with a foreign key

So, I'm not sure why this is failing. I have a model Card that has a billing profile. Then I have defined a str function on it. The field it refers to has a foreign key to another model's email field.

class Card(models.Model):
    billing_profile         = models.ForeignKey(BillingProfile)
    stripe_id               = models.CharField(max_length=120)

    def __str__(self):
        return "{}".format(self.billing_profile__email)

class BillingProfile(models.Model):
    user        = models.OneToOneField(User, null=True, blank=True)
    email       = models.EmailField()

    def __str__(self):
        return self.email

Whenever I don't comment out the str method, I get 'Card' object has no attribute 'billing_profile__email'. When I put return self.billing_profile instead of return self.billing_profile__email it doesn't error out and it gives me the right email. Why is that? Why doesn't billing_profile__email work?

Upvotes: 0

Views: 498

Answers (1)

neverwalkaloner
neverwalkaloner

Reputation: 47364

You should use . instead of __ inside class:

def __str__(self):
    return "{}".format(self.billing_profile.email)

Double underscore syntax for related fields access is only using in django queryset, but in normal python code you should use . to access object's attribute.

Upvotes: 2

Related Questions