获取Django中另一个对象的相关对象列表的最佳实践

时间:2015-10-07 20:44:52

标签: python django

我有这样的感觉。它相当简单,只需要获得一些与之相关的论坛帖子和评论。

def thread_detail(req, id):
    thread = Thread.objects.get(pk=id)
    comments = thread.comment_set.all()
    return render(req, 'threads/thread.html', {'thread': thread, 'comments': comments})

但我不确定这是你应该在Django中这样做的方式。使用DetailView或将SingleObjectMixin和ListView混合为shown in docs

是否更好?

2 个答案:

答案 0 :(得分:1)

如果您不想,则无需使用基于类的视图。基于函数的视图的优点是它非常简单易懂。基于类的视图的优点是您可以利用视图中的其他功能,例如分页。

就我个人而言,我认为基于功能的视图比使用SingleObjectMixinListView的文档中的示例更容易理解。

我建议您使用get_object_or_404,以便在没有该主键的线程时向用户显示404页面。

from django.shortcuts import get_object_or_404

thread = get_object_or_404(Thread, pk=id)

答案 1 :(得分:0)

我经常认为这更像是个人偏好。

来自django的良好实践书。 '两个DJANGO 1.8'

  

FBV的简单性是以代码重用为代价的:FBV   没有相同的能力从超类继承   CBV这样做。 ey确实具有更明显功能的优势   在自然界中,它适用于许多有趣的策略

我同意@Alasdair,您的基于功能的视图更容易理解。

我只在代码中更改它:

def thread_detail(req, id):
    thread_qs = Thread.objects.filter(pk=id).prefetch_related('comment_set')
    if not thread_qs:
        raise Http404
    else:
        thread = thread_qs[0]
        return render(req, 'threads/thread.html', {'thread': thread})

并在html中,只是线程注释上的迭代器:

{%for comment in thread.comment_set.all %}
    {{comment}}
{%endfor%}

因为这是一种很好的做法,我认为这也有助于提高绩效。