Joe Howard
Joe Howard

Reputation: 307

How to access a related object's field

I am trying to store the campus that the teacher is associated with in the device model. I tried creating a model method but was unable to access it from the related model.

class Campus(models.Model):
    name = models.CharField(max_length=20)

    def __str__(self):
        return self.name

class Teacher(models.Model):
    campus = models.OneToOneField(Campus, on_delete=models.CASCADE, default="Not Assigned")

class Device(models.Model):
    owner = models.ForeignKey(Teacher, on_delete=models.CASCADE)

Upvotes: 2

Views: 1660

Answers (1)

brno32
brno32

Reputation: 424

Given your foreign key and one to one field, the queries you want would look like

device_queryset = Device.objects.all()

for device in device_queryset:
    print(device.owner.campus.name)

On an instance of Device, you can access the teacher model by referencing the field owner, which is a foreign key to Teacher. Once you are on Teacher, you can access its attributes like campus, and so on.

You may find the documentation on field lookups useful https://docs.djangoproject.com/en/2.1/ref/models/querysets/#id4

Upvotes: 3

Related Questions