如何使用DetailView编写与Django相关的查询

时间:2015-11-27 08:31:52

标签: python django django-views

如何在Django中编写一个DetailView,它有其他相关的查询?

以下是我的例子:

class DistributionDetailView(DetailView):
    model = Distribution
    template_name = 'projects/view_distribution.html'

    def get_context_data(self, **kwargs):
        context = super(DistributionDetailView,
                        self).get_context_data(**kwargs)
        context['weekly_attendance'] = WeeklyAttendance.objects.filter(
            distibution_name=Distribution)
        context['sales_data'] = SalesData.objects.filter(
            distibution_name=Distribution)
        context['theatrical_release'] = TheatricalRelease.objects.filter(
            distibution_name=Distribution)
        return context

2 个答案:

答案 0 :(得分:0)

Distribution是模型类,您无法在filter()中使用它。在get_context_data方法中,您可以使用self.object访问当前对象,例如:

context['weekly_attendance'] = WeeklyAttendance.objects.filter(
        distibution_name=self.object)

答案 1 :(得分:0)

您可以在大多数通用视图中使用self.object访问该对象:

class DistributionDetailView(DetailView):
    model = Distribution
    template_name = 'projects/view_distribution.html'

    def get_context_data(self, **kwargs):
        context = super(DistributionDetailView,
                        self).get_context_data(**kwargs)
        context['weekly_attendance'] = WeeklyAttendance.objects.filter(
            distibution=self.object)
        context['sales_data'] = SalesData.objects.filter(
            distibution=self.object)
        context['theatrical_release'] = TheatricalRelease.objects.filter(
            distibution=self.object)
        return context