Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django - model unicode() show foreignkey object attribute

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".

like image 512
MD6380 Avatar asked Feb 22 '13 01:02

MD6380


People also ask

What is a foreign key in Django?

What is ForeignKey in Django? ForeignKey is a Field (which represents a column in a database table), and it’s used to create many-to-one relationships within tables. It’s a standard practice in relational databases to connect data using ForeignKeys. What’s the difference between foreign key and primary key?

What is the use of foreign key in SQL?

ForeignKey is a Field (which represents a column in a database table), and it’s used to create many-to-one relationships within tables. It’s a standard practice in relational databases to connect data using ForeignKeys. What’s the difference between foreign key and primary key? The primary key defines the unique value for a row in a table.

Where to place foreignkey in the book model?

In other words, ForeignKey should be placed in the Child table, referencing the Parent table. NOTE - Without an Author, there can't be Book (Author is parent, Book is child model) In given example – One Author can write multiple books, and one Book can be written only by one Author. That’s why we placed ForeignKey in the Book model.


1 Answers

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)     
like image 107
Michael Place Avatar answered Oct 07 '22 12:10

Michael Place