django - model unicode() show foreignkey object attribute

django, django-admin, django-models, python, python-2.7

Solution

You can indeed, by referring to the attribute using the 'dot' syntax. Here is what you want:

def __unicode__(self):
   return '%s %s' % (self.app_id.app_name, self.environ_name)     

Problem

I'm new to Django and have an Application model and a Environment model. The Environment has the Application as a foreignkey. I know that I need to write a unicode() method for a human-readable representation of the model, but is there a way to get an attribute from the foreignkey object to display as part of the string? ``` class Application(models.Model): app_id = models.IntegerField(primary_key=True) app_name = models.CharField(max_length=200) app_description = models.CharField(max_length=2000, blank=True) def __unicode__(self): return self.app_name class Environment(models.Model): app_id = models.ForeignKey(Application, db_column='app_id') environ_id = models.IntegerField(max_length=6) environ_name = models.CharField(max_length=200) def __unicode__(self): return '%s %s' % (application__app_name, self.environ_name) ``` I want the Environment model to be represented as "app_name environ_name". Update: The reason why I want to display the Environment model as "app_name environ_name" it so that it's more clear to the user when entering data on the admin pages. For example, app_name would be "NavSystem" and environ_name would be "DEV1", so having the Environment model represented as "NavSystem DEV1" is more useful than just "DEV1".

Original source