Django query get parent related models from the child models


Get parent models queried from child models in Django is possible and easy. For example, we have this parent – child models relation :

1
2
3
4
5
6
7
8
9
10
11
12
13
from django.db import models

class Company(models.Model):
    name = models.CharField(max_length=255)


class Insurance(models.Model):
    company = models.ForeignKey(Company)
    package = models.IntegerField(max_length=255)


class Client(models.Model):
    insurance = models.ForeignKey(Insurance)


Now, we want to get Insurance and Company value from Client models. So, we can use “select_related” feature.

1
2
3
4
5
6
7
8
# this will contain <Client data …>
clients = Client.objects.select_related().get(id=1)

# this will contain <Insurance data … >
insurance = clients.insurance

# this will contain <Company data … >
company = insurance.company

By using select_related, we can access parent models from it’s child.


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.