wmfox3
wmfox3

Reputation: 2221

Accessing an attribute of a foreignkey field in a django model

I'm trying to create a model method that returns an attribute of a foreign key. In this case, I want get_place_name() to return the pretty_name field of the place model. But when I do so, I get an attribute error: "'NoneType' object has no attribute 'pretty_name'"

class CalendarEvent(models.Model):

    event_id = models.CharField( max_length=22, db_index=True, unique=True )
    event_name = models.CharField( max_length=255, db_index=True )
    place = models.ForeignKey( Place, blank=True, null=True  )

    def __unicode__(self):
        return self.event_name

    def get_place_name(self):
        return "%s" % self.place.pretty_name

Upvotes: 0

Views: 103

Answers (1)

dgel
dgel

Reputation: 16786

Well, you have null=True for your place foreign key. Is it possible that for the particular CalendarEvent that you are calling, place is indeed None? In which case the error would be accurate. You could handle that more gracefully by modifying your get_place_name method:

def get_place_name(self):
    if self.place:
        return self.place.pretty_name

Upvotes: 3

Related Questions