San*_*ack 4 django filter primary-key detailview
嗨,我确信这有一个简单的解决方案,但我找不到它!必须一直需要它!
为了学习 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']
Run Code Online (Sandbox Code Playgroud)
我有模板和网址,将列出所有主题。
当我看到该列表时,我希望能够单击它[我可以这样做]并拥有该主题以及与其链接的所有事实(尽管外键出现)[技术上是否会被描述为子级的过滤查询集对象?] 我正在使用详细视图。
网址
url(r'^(?P<pk>\d+)/$', TopicDetailView.as_view(), name='facts'),
Run Code Online (Sandbox Code Playgroud)
这是详细视图的代码。我知道它知道 pk,因为当我取出额外上下文过滤器(并且只需使用 .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
Run Code Online (Sandbox Code Playgroud)
如果我在模板中添加一些逻辑和过滤器,我就可以做到这一点,但这对我来说似乎不太合适,我觉得我必须能够通过添加正确的额外上下文来轻松地做到这一点。
帮助一些可怜的新手!非常感谢。
'pk'只是一个字符串。你的意思是self.kwargs['pk']。
但实际上你根本不想这样做。超类已经将 Topic 对象添加到上下文中:并且您在 Topic 和 Fact 之间建立了关系。可以在模板中遍历这个关系:
{% for fact in topic.fact_set.all %}
...
{% endfor %}
Run Code Online (Sandbox Code Playgroud)
所以你不需要覆盖get_context_data.
| 归档时间: |
|
| 查看次数: |
2996 次 |
| 最近记录: |