Search code examples
pythondjangodjango-modelsforeign-keysdjango-queryset

Using Relationship Based Data in Model Definition - Django


I want to make the string representation of a field show data based on a JOIN, for instance:

  • For Penciler - I want the string representation to resolve to John Doe (DC) - But the publisher value in that class is a Foreign Key - How do I reference the publisherName?
from django.db import models

class Series(models.Model):
    seriesId = models.AutoField(primary_key=True)
    series_name = models.CharField(max_length=300)
    publisher = models.ForeignKey('Publisher', on_delete = models.PROTECT)
    first_published = models.DateField()
    last_published = models.DateField()
    discontinued = models.BooleanField(default=False)
    def __str__(self):
        return f'{self.series_name} - {self.publisher} ({self.first_published - self.last_published})'
    class Meta:
        ordering = ['publication_year','title']

class Publisher(models.Model):
    publisherId = models.AutoField(primary_key=True)
    publisherName = models.CharField(max_length=250, null=False)
    def __self__(self):
        return self.publisherName
    
class Penciler(models.Model):
    pencilerID = models.AutoField(primary_key=True)
    pencilerName = models.CharField(max_length=200)
    publisher = models.ForeignKey('Publisher', on_delete= models.PROTECT)
    def __str__(self):
        return self.pencilerName (self.publisher)

Solution

  • You can access the related Publisher instance through the ForeignKey field and get the publisherName in the __str__() method so:

    def __str__(self):
        publisher_name = self.publisher.publisherName
        return f'{self.pencilerName} ({publisher_name})'
    

    Additionally, I'd recommend you to use string formatting, such as using f-strings.