Chetan Badgujar
Chetan Badgujar

Reputation: 55

Fetch child data with parents in Django queries

I have two Model Product and ProductBundle. ProductBundle have a foreign key of Product Model. How can I access a list of all product with there productbundle.

class Product(models.Model):
    title = models.CharField(verbose_name="Product Title", max_length=500)

class ProductBundle(models.Model):
    product = models.ForeignKey(Product,on_delete=models.CASCADE,related_name="product")
    bundle_product = models.ForeignKey(Product,on_delete=models.CASCADE,related_name="bundle_product",default="")
    quantity = models.IntegerField(default="1")

I want to fetch all product with there productbundle ids like parent to childs in a single variable.

Thanks.

Upvotes: 0

Views: 6111

Answers (2)

robtus88
robtus88

Reputation: 490

You should change the related_name of product inside ProductBundle to something like bundles and then you can go product.bundles.all() to access all ProductBundle related to a Product

edit to filter all products if they have a ProductBundle

assuming you are using bundles as related_name: Product.objects.filter(bundles__isnull=False).distinct()

Upvotes: 1

rollingthedice
rollingthedice

Reputation: 1125

You already have ProductBundle objects as a Related objects reference for each Product.

Assuming you do products = Product.objects.all() you can access each product's bundles by doing:

for product in products:
    product_bundles = product.productbundle_set.all()

Edit based on comment:

If you want to show all products with their bundles in a template you can do almost the same thing. In your view get all products within a variable, for example products = Product.objects.all() and pass it to the template. Assuming your variable is called products you can do:

{% for product in products %}
    <h1>{{product.title}}</h1>
    <h1>Bundles:</h1>
    {% for bundle in product.productbundle_set.all %}
        <h2>{{bundle.quantity}}</h2>
    {% endfor %}
{% endfor %}

Upvotes: 3

Related Questions