Reputation: 1945
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
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