python - 如何从嵌套的 for 循环中访问数据
问题描述
我想在 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中还是写在html文件中的django模板中?
我是网络开发的新手,所以任何方向都会有所帮助。谢谢!
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)
解决方案
要访问相关对象,请使用相关管理器。
在这种情况下,相关经理是spot.spotlinks_set
。
{% for spot in spots %}
<div>
<h2>{{ spot.title }}</h2>
</div>
<!-- {% for link in links %} --> <!-- Replace this -->
{% for spotlink in spot.spotlinks_set.all %} <!-- with this -->
<div>
<!-- <h3>{{ link.url }}</h3> --> <!-- Replace this -->
<h3>{{ spotlink.link.url }}</h3> <!-- with this -->
</div>
{% endfor %}
{% endfor %}
参考:https ://docs.djangoproject.com/en/3.2/ref/models/relations/
推荐阅读
- angular - angular 6 获取 ngmodel 绑定名称
- r - xaringan:更改特定块的代码背景
- elasticsearch - 通过消息 logstash 创建一个字段
- linux - 在 Linux x64 上禁用 NX
- reporting-services - CRM - 基于其他行的 SSRS FetchXML 行过滤
- php - 从查询 laravel 计算行数
- here-api - 在选择“选择视图”选项之前,这里的地图不会显示
- java - 允许 Spring Security + Cas Auth + 静态用户列表
- c - 在具有 4 个线程的程序上调用 pthread_cond_signal 时,同一线程获取互斥锁
- python - 使用正则表达式将自由文本解析为 dict