问题描述
我想在Campaign DetailView模板中显示产品.
I want to display products in a Campaign DetailView template.
在我的项目中,每个广告系列都有一个包含产品的商店,因此流程就像
In my project each campaign has a shop which contains products, so the flow is like,
广告活动->商店->产品
Campaign --> Shop --> Products
广告系列模型.py
class Campaign(models.Model):
team = models.OneToOneField(Team, related_name='campaigns', on_delete=models.CASCADE, null=True, blank=True)
shop = models.OneToOneField(shop_models.Shop, on_delete=models.CASCADE, null=True, blank=True)
商店模型.py
class Product(models.Model):
title = models.CharField(max_length=100)
description = models.CharField(max_length=700, null=True, blank=True)
price = models.DecimalField(max_digits=10, decimal_places=0)
class Shop(models.Model):
product = models.OneToOneField(Product, related_name='shop_product', on_delete=models.CASCADE, null=True, blank=True)
product2 = models.OneToOneField(Product, related_name='shop_product2', on_delete=models.CASCADE, null=True, blank=True)
product3 = models.OneToOneField(Product, related_name='shop_product3', on_delete=models.CASCADE, null=True, blank=True)
DetailView
class CampaignDetail(DetailView):
model = Campaign
form_class = CampaignForm
pk_url_kwarg = 'pk'
context_object_name = 'object'
template_name = 'campaign_detail.html'
模板
{% for item in obj.shop_set.all %}
<div class="plan">
<a href="">
<h4>{{ item.title }}</h4>
<h5>{{ item.price }}</h5>
<img src="{{ item.image.url }}" alt="">
</a>
</div>
该模板中的字段原来为空.任何帮助将不胜感激.
Fields turned out to be empty in the template.Any help would be appreciated.
推荐答案
它们与 OneToOneField ,那么您可以通过广告系列详细信息视图访问shop的值,如下所示:
As they are related by OneToOneField, then you can access the values of shop from campaign details view like this:
{{ obj.shop }}
如果您要访问产品,请按照以下步骤操作:
And if you want to access the products, then do it like this:
{{ obj.shop.product.title }}
{{ obj.shop.product.price }}
{{ obj.shop.product2.title }}
{{ obj.shop.product2.price }}
{{ obj.shop.product3.title }}
{{ obj.shop.product3.price }}
更新
好吧,在这种情况下,我建议使用 ManyToMany 产品与商店之间的关系.因此,可以将一个产品分配给多个商店,也可以将一个商店分配给多个产品.然后,您可以这样定义关系:
Update
Well, in that case I would recommend using ManyToMany relation between Product and Shop. So that, a product can be assigned to multiple shops, or a shop can be assigned to multiple product. Then you can define the relation like this:
class Shop(models.Model):
products = models.ManyToManyField(Product)
,如果您想遍历商店的产品,可以这样做:
and if you want iterate through products for a shop, you can do it like this:
{% for product in obj.shop.products.all %}
{{ product.title }}
{{ product.name }}
{% endfor %}
这篇关于如何访问Django模板中的外键?(详细视图)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!