我无法尝试从模板中访问外键元素。我试图使用类视图传递多个上下文:
class HomeView(ListView):
template_name = "homepage/home.html"
queryset = Author.objects.all()
def get_context_data(self, **kwargs):
context = super(HomeView, self).get_context_data(**kwargs)
context['author_links'] = Author_link.objects.all()
context['categories'] = Category.objects.all()
context['extra_links'] = Extra_link.objects.all()
context['poems'] = Poem.objects.all()
return context
我的models.py文件:
class Author(models.Model):
name = models.CharField(max_length=30)
def __str__(self):
return self.name
class Author_link(models.Model):
url_text = models.CharField(max_length=100)
url = models.CharField(max_length=200)
author = models.ForeignKey(Author)
def __str__(self):
return self.url_text
class Category(models.Model):
name = models.CharField(max_length=100)
description = models.TextField()
class Meta:
verbose_name_plural = 'categories'
def __str__(self):
return self.name
class Extra_link(models.Model):
url_text = models.CharField(max_length=100)
url = models.CharField(max_length=200)
category = models.ForeignKey(Category)
def __str__(self):
return self.url_text
然而,当我试图遍历上下文时,我似乎无法访问每个项目的外键:
{% for author in object_list %}
<li class = "collection-item">
<ul class="collapsible" data-collapsible="accordion">
<li>
<div class="collapsible-header">{{author.name}}</div>
<div class="collapsible-body">
{% for item in author.item_set.all %}
<p>{{item.url}}</p>
{% endfor %}
</div>
</li>
</ul>
</li>
{% endfor %}
我想要做的是循环作者,同时在每个作者循环下通过与每个作者相关联的网址。
答案 0 :(得分:0)
你有
的地方{% for item in author.item_set.all %}
<p>{{item.url}}</p>
{% endfor %}
你应该有像
这样的东西{% for item in author.author_link_set.all %}
<p>{{item.url}}</p>
{% endfor %}
此管理员(author.author_link_set
)已添加到每位作者,因为有Author_link
到Author
的外键。
旁注:python中类名的约定是Pascal Case,例如AuthorLink
而不是Author_link
。我提到这一点是因为我不能100%肯定我是否正确猜到了作者的反向关系的名称(可能是author.authorlink_set
,我从未在模型名称中看到过下划线 - django可能会做某事特殊情况)