[英]related_name doesn't work in Django about some different objects
I have trouble about calling related models.我在调用相关模型时遇到问题。 my models:我的模型:
class Product(models.Model):
product_model = models.CharField(max_length=255, default='')
product_url = models.SlugField(max_length=200, default='')
product_category = models.ForeignKey(Category,
on_delete=models.CASCADE,
default='',
null=True,
related_name="products",
)
product_subcategory = models.ForeignKey(Subcategory,
on_delete=models.CASCADE,
default='',
null=True,
related_name="products",
)
description = tinymce_models.HTMLField(verbose_name="text")
product_img = models.ImageField(upload_to="product_imgs/" ,default='')
class Stock(models.Model):
ONE = '1'
TWO = '2'
FREE = 'free'
PRODUCT_SIZES = [
(ONE, '1'),
(TWO, '2'),
(FREE, 'free'),
]
size = models.CharField(max_length=60,default=" ", choices=PRODUCT_SIZES)
quantity = models.PositiveIntegerField(default=0)
price = models.FloatField(default=0, null=True)
product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name="pro")
each product can has 3 stock object with different sizes, I want show a product quantity in stock with all sizes, for example (size1 has 10, size2 has 10, sizefree has 10, I want show 30)每个产品可以有 3 个不同尺寸的库存对象,我想显示所有尺寸的库存产品数量,例如(size1 有 10 个,size2 有 10 个,sizefree 有 10 个,我想要显示 30 个)
my views:我的观点:
def products(request):
if request.user.is_staff or request.user.is_superuser:
products = Product.objects.all()
ctx = {'products':products}
return render(request, 'staff/products_list.html',ctx)
else:
return redirect('/staff')
and my html和我的 html
{% for product in products %}
<td class="text-info">
{% for product in product.pro.quantity.all %}
{{product}}
{% endfor %}
</td>
{% endfor %}
how can I solve this problem ?我怎么解决这个问题 ?
You have set related_name="pro"
this means pro
is a " Related Manager ".您已设置related_name="pro"
这意味着pro
是“相关经理”。 Hence writing product.pro.quantity
does not make any sense.因此,编写product.pro.quantity
没有任何意义。 Instead you want to write something like product.pro.all
and loop over it to get the related instances:相反,您想编写类似product.pro.all
并循环遍历它以获取相关实例:
{% for product in products %}
<td class="text-info">
{% for stock in product.pro.all %}
{{ stock.quantity }}
{% endfor %}
</td>
{% endfor %}
Note : Furthermore
pro
does not make much sense as the related name here, even the defaultstock_set
was a better related name here.注意:此外pro
在这里的相关名称没有多大意义,即使默认的stock_set
在这里也是一个更好的相关名称。 Consider changing the related name to something more descriptive, example:stocks
.考虑将相关名称更改为更具描述性的名称,例如:stocks
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.