问题描述
我有两个Model产品和ProductBundle。 ProductBundle具有产品模型的外键。我该如何访问带有productbundle的所有产品的列表。
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 likeparent to childs in a single variable.
谢谢。
推荐答案
您已经拥有 ProductBundle
对象作为 。
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()
根据评论进行编辑:
如果要在模板中显示捆绑销售的所有产品,几乎可以一样。在您的视图
中获取变量中的所有产品,例如 products = Product.objects.all()
并将其传递模板。假设您的变量称为产品
,您可以执行以下操作:
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查询中与父母一起获取子数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!