我正在尝试打印品牌和它的链接,我正在使用嵌套循环,但它没有显示正确的输出
这是我的代码
{% for brand_report in brand_reports %}
<h1> REPORT for Brand: {{ brand_report.brand.name }}</h1>
{% for link in brand_report.links.all %}
<h3>link:</h3><a href="{{ link.url }}">{{link.url}}</a>
{% endfor %}
{% endfor %}
所需的输出
REPORT for Brand: SizCom
link:
https://www.justdial.com/Kozhikode/SizCom-Near-to-Big-Bazaar-Calicut-City/0495PX495-X495-151217184614-Z4I2_BZDET
REPORT for Brand: SizCom
link:
https://www.justdial.com/Kozhikode/SizCom-Near-to-Big-Bazaar-Calicut-City/0495PX495-X495-151217184614-Z4I2_BZDET
但我得到这样的输出
REPORT for Brand: SizCom
REPORT for Brand: SizCom
link:
https://www.justdial.com/Kozhikode/SizCom-Near-to-Big-Bazaar-Calicut-City/0495PX495-X495-151217184614-Z4I2_BZDET
link:
https://www.justdial.com/Kozhikode/SizCom-Near-to-Big-Bazaar-Calicut-City/0495PX495-X495-151217184614-Z4I2_BZDET
不知道我做错了什么
模型:
class Brand(models.Model):
"""For the brand"""
name = models.CharField(max_length=500)
description = models.TextField(blank=True, null=True)
context = models.ManyToManyField(Context, blank=True)
variation = models.ManyToManyField('BrandVariation', blank=True, related_name='brand')
status = models.BooleanField(default=False)
def __str__(self):
return self.name
class ResultLink(models.Model):
"""for results"""
url = models.URLField(max_length=1000)
country = models.ForeignKey(Country, blank=True, null=True)
parent_site = models.ForeignKey(Domain, on_delete=models.CASCADE, blank=True, null=True)
variation = models.ForeignKey(BrandVariation, on_delete=models.CASCADE, blank=True, null=True)
brand = models.ForeignKey(Brand, on_delete=models.CASCADE, blank=True, null=True, related_name='link')
date = models.DateField(auto_now_add=True)
def __str__(self):
return "%s" % self.url
class BrandReport(TimeStampedModel):
""""""
brand = models.ForeignKey(Brand, related_name='counterfeit_report')
links = models.ManyToManyField(ResultLink, blank=True)
class Meta:
verbose_name = "Brand Report"
观点:
def view(request,brands):
template_path = 'profile_brand_report.html'
brand_reports = BrandReport.objects.filter(brand__id__in=brands)
context = {'brand_reports': brand_reports}
html = render_to_string(template_path, context)
答案 0 :(得分:0)
我重新创建了你的项目。你唯一错过的是你的观点。所以我想这就是你的问题所在。以下是我的观点:
def demoview(request):
objs = BrandReport.objects.all()
c = {
"brand_reports": objs,
}
return render(request, "blog/demoview.html", c)
这是我的模板:
{% for brand_report in brand_reports %}
<h1> REPORT for Brand: {{ brand_report.brand.name }}</h1>
{% for link in brand_report.links.all %}
<h3>link:</h3><a href="{{ link.url }}">{{link.url}}</a>
{% endfor %}
{% endfor %}
我的结果正是你所期望的。请检查您的观点。
答案 1 :(得分:0)
你显然没有任何相关链接的第一个BrandReport和第二个带有两个相关链接的BrandReport - 检查你的数据库。
FWIW,我实际上并没有得到你的BrandReport模型,因为你已经拥有了ResultLink中的Brand的外键。您的BrandReport模型不仅是多余的(据我们所知),而且还很脆弱,因为它允许任何ReportLink与任何品牌相关联,而不考虑ReportLink.brand
约束。