首页 > 解决方案 > 如何从嵌套的 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)

标签: pythondjangodjango-modelsdjango-viewsdjango-templates

解决方案


要访问相关对象,请使用相关管理器。

在这种情况下,相关经理是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/


推荐阅读