Fetch child data with parents in Django queries

后端 未结 2 1649
面向向阳花
面向向阳花 2021-01-29 04:28

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         


        
相关标签:
2条回答
  • 2021-01-29 04:39

    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 %}
    
    0 讨论(0)
  • 2021-01-29 04:46

    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()

    0 讨论(0)
提交回复
热议问题