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.
c
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 %}
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()