嗨,我确定这有一个简单的解决方案,但我找不到它!必须始终要求它!
要学习django我正在为我编写简单的应用程序来记录我的学习要点。所以我有两个模型:
class Topic(models.Model):
title = models.CharField(max_length=40)
def __unicode__(self):
return self.title
class Meta():
ordering = ['title']
class Fact(models.Model):
note = models.CharField(max_length=255)
topic = models.ForeignKey('Topic')
def __unicode__(self):
return self.note
class Meta():
ordering = ['note']
我有模板和网址,列出所有主题。
当我看到该列表时,我希望能够点击它[我可以做到]并将该主题和所有与之相关的事实联系起来(thourgh外键出现)[技术上会将其描述为过滤查询一组子对象?]我正在使用detailview。
URL
url(r'^(?P<pk>\d+)/$', TopicDetailView.as_view(), name='facts'),
以下是详细视图的代码。知道我知道它知道pk,因为当我取出extracontext过滤器时它显示正确的页面(并且只需要.all())。但无论我尝试多少种方式,我都无法参考。我想要这样的东西......
class TopicDetailView(DetailView):
model = Topic
template_name = 'study/topic_facts.html'
def get_context_data(self, **kwargs):
# Call the base implementation first to get a context
context = super(TopicDetailView, self).get_context_data(**kwargs)
# Add in a QuerySet of all the books
context['fact_list'] = Fact.objects.filter(topic='pk')
return context
如果我在模板中添加了一些逻辑和过滤器,但是这对我来说似乎不太合适,我可以做到这一点,我觉得我必须能够通过添加正确的额外上下文来轻松完成。
帮助一些可怜的新手出去!非常感谢。
答案 0 :(得分:3)
'pk'
只是一个字符串。你的意思是self.kwargs['pk']
。
但实际上你根本不想这样做。超类已经将Topic对象添加到上下文中:并且您在Topic和Fact之间存在关系。您可以在模板中遍历此关系:
{% for fact in topic.fact_set.all %}
...
{% endfor %}
所以您不需要覆盖get_context_data
。