Filter queryset child models related by parent models in Django


As I explained in Django query get parent related models from the child models, we can made query parent models from child models relationship.

Now, we will doing filter queryset of child models by parent models value. Given models example :

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)


For example data :

1
2
Company.name = ["AXA", "Travel Insurer", "Dental Insurance"]
Insurance.package = ["1", "2", "3"]

Now, we want to retrieve Client that have Insurace package “1” and Company Name “AXA”. We can use filter() here.

1
clients = Client.objects.filter(insurance__package=1, insurance__company__name="AXA")

With filter(), we can access related Models key and get filtering from its.


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.