def __str__(self):
return _(u'#{0}, {1}, {2}').format(
self.pk,
self.lead and self.lead.customer_name or None,
self.lead and self.lead.customer_phone or None
)
lead = models.ForeignKey('Lead', blank=True, null=True,)
AttributeError: 'NoneType' object has no attribute 'customer_name'
--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/e5e2a0ea-8fb0-4acb-a84d-edccc64d7a62%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
You can reroll your original example like this:
def __str__(self):
pk = self.pk
customer_name = None
customer_phone = None
try:
customer_name = self.lead.customer_name
customer_phone = self.lead.customer_phone
except AttributeError:
pass
return _(u'#{0}, {1}, {2}').format(
pk,
customer_name,
customer_phone,
)
Much more pythonic, IMO.
-James
Yes, it's a bit more verbose, but much easier to follow. Hope it helps.
-James
--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAKzdcNkP-3JrfgQJ70g4Dj6Wd-LAc6Rxcy0MHxJrqbKiRK2pyw%40mail.gmail.com.
You can definitely do it that way if all you need to do is check if values exist and provide a default if they don't. I do this all the time for my __str__() methods as well.
You also mentioned similar situations that may require more logic checks (variables depending on each other or printing computed values), then the try/except strategy is likely more flexible.
-James
--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAKzdcN%3Dr9gA3diGW0t8tu0z03CoUp%2BhZOm3rfaog35X5rxX5MA%40mail.gmail.com.