在 Django 查询中与父母一起获取子数据 [英] Fetch child data with parents in Django queries
问题描述
我有两个 Model Product 和 ProductBundle.ProductBundle 有一个 Product Model 的外键.如何使用产品包访问所有产品的列表.
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")
我想获取所有带有 productbundle id 的产品,例如单个变量中的父级到子级.
I want to fetch all product with there productbundle ids like parent to childs in a single variable.
谢谢.
推荐答案
您已经拥有 ProductBundle
对象作为 每个Product
的相关对象引用.
You already have ProductBundle
objects as a Related objects reference for each Product
.
假设您执行 products = Product.objects.all()
,您可以通过执行以下操作访问每个产品的捆绑包:
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()
根据评论进行
如果您想在模板中显示所有产品及其捆绑包,您几乎可以做同样的事情.在您的 view
中获取变量中的所有产品,例如 products = Product.objects.all()
并将其传递给模板.假设您的变量名为 products
,您可以执行以下操作:
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 %}
这篇关于在 Django 查询中与父母一起获取子数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!