【发布时间】:2021-12-15 10:33:24
【问题描述】:
我想在下面的 html 中显示多个“点”,并在每个点内显示与每个特定点关联的“链接”。
如何编写逻辑来显示每个位置的特定链接?
html
{% for spot in spots %}
<div>
<h2>{{ spot.title }}</h2>
</div>
{% for link in links %}
<div>
<h3>{{ link.url }}</h3>
</div>
{% endfor %}
{% endfor %}
我的模型如下。 SpotLinks 是 Links 和 Spots 表的中间表。
models.py
class Spots(models.Model):
title = models.CharField(max_length=155)
slug = models.SlugField(unique=True, max_length=155)
class Links(models.Model):
title = models.CharField(unique=True, max_length=155, blank=True)
url = models.CharField(max_length=75, blank=True)
class SpotLinks(models.Model):
link = models.ForeignKey('Links', models.DO_NOTHING)
spot = models.ForeignKey('Spots', models.DO_NOTHING)
class Articles(models.Model):
title = models.CharField(max_length=155)
slug = models.SlugField(unique=True, max_length=155)
summary = models.TextField(blank=True, null=True)
class ArticleSpots(models.Model):
article = models.ForeignKey('Articles', models.DO_NOTHING)
spot = models.ForeignKey('Spots', models.DO_NOTHING)
我在views.py 中尝试了links = Links.objects.filter(spotlinks__spot=spots),但由于斑点中有多个斑点,它没有被过滤。
逻辑是写在views.py中还是作为django模板写在html文件中?
我是 Web 开发的新手,所以任何方向都会有所帮助。谢谢!
views.py
def article(request, slug):
article = get_object_or_404(Articles, slug=slug)
spots = Spots.objects.filter(articlespots__article=article).distinct()
links = Links.objects.filter(spotlinks__spot=spots)
context = {
'spots': spots,
'article': article,
'links': links}
return render(request, 'articletemplate.html', context)
【问题讨论】:
-
for link in linkslink.url→for spotlink in spot.spotlinks_set.all()spotlink.link.url -
谢谢@aaron。我试过了,它给了我以下错误.. TemplateSyntaxError 无法解析剩余部分:'spot.spotlinks_set.all()'中的'()'
-
试试
spot.spotlinks_set.all不带()。
标签: python django django-models django-views django-templates