How to access child model from a parent model using Django ORM?

Here are my models:

class Collection(models.Model):
    title = models.CharField(max_length=255)
    featured_product = models.ForeignKey(
        'Product', on_delete=models.SET_NULL, null=True, related_name='+')


class Product(models.Model):
    description = models.TextField()
    unit_price = models.DecimalField(max_digits=6, decimal_places=2)
    inventory = models.IntegerField()
    collection = models.ForeignKey(Collection, on_delete=models.PROTECT)

I have two models here, one of which is the parent (Collection), and the other is the child (Product).

So if I need to filter the queryset based on the title attribute of the Collection class, I can type a queryset like this.

query_set = Product.objects.filter(collection__title = 'beauty')

Notice: Here I am accessing the parent using the child; the question is, how can I do the opposite?

I tried this line of code but i got an error saying:Cannot resolve keyword 'product_set' into field. query_set = Collection.objects.filter(product_set__inventory__lt=10)

I believe the error has to do with how you've set the related name for "Product" in the "Collection" model. When you use the filter() API you need to reference the child component using either the related name, or by using its actual name and leaving related name unset.

Look at the note in green about many to many fields here in the docs

Try this:

class Collection(models.Model):
title = models.CharField(max_length=255)
featured_product = models.ForeignKey(
    'Product', on_delete=models.SET_NULL, null=True, related_name='product_set') 

class Product(models.Model):
description = models.TextField()
unit_price = models.DecimalField(max_digits=6, decimal_places=2)
inventory = models.IntegerField()
collection = models.ForeignKey(Collection, on_delete=models.PROTECT)

And then:

queryset=Collections.objects.filter(product_set__inventory__lt=10)
Back to Top