Is it possible to access the value of different tables connected by ForeignKey Django

Viewed 26

So I've created a little database relationship for the question:

from django.db import models

# Create your models here.


class Poll(models.Model):

    title = models.CharField(max_length=255)
    date_created = models.DateTimeField(auto_now_add=True)
    is_active = models.BooleanField(default=True)

    def __str__(self):

        return self.title



class Option(models.Model):

    title= models.CharField(max_length=50)
    poll = models.ForeignKey(Poll, on_delete=models.CASCADE)
    desc = models.CharField(max_length=255)

    def __str__(self):

        return self.title



class Voter(models.Model):

    name = models.CharField(max_length = 255)
    option = models.ForeignKey(Option, on_delete=models.CASCADE)

    def __str__(self):

        return f'{self.name} - {self.option}'

So I have 2 questions:

  1. Is it possible to access the value of Option model's desc field from Voter model's __str__ function ?

  2. Is it possible to access the value of Poll model's date_created field from Voter model's __str__ function ?

Thank you so much!

1 Answers

you can access related models and fields with ., and because of your model's relations, you can do like below.

1- {self.option.desc}

2- {self.option.poll.date_created}

Related