从Django中的模型类中获取数据

时间:2017-08-07 06:28:20

标签: python django

我有一个特定频道的DetailView。此处列出了该频道的所有数据。有一个名为'ExecutionLog'的模型类。目前,除了来自'ExecutionLog'模型类的数据外,所有其他数据都显示在详细视图中。

该课程属于“基于班级的视图”,这对我来说是全新的。我无法理解究竟发生了什么。

DetailView类视图:

class ChannelDetailView(LoginRequiredMixin, SuperAdminMixin, ChannelView, DetailView):
    def get_context_data(self, *args, **kwargs):
        context = super(ChannelDetailView, self).get_context_data(*args, **kwargs)

        if 'date' in self.request.GET:
            d = self.request.GET['date']
            date = datetime.datetime.strptime(d, "%Y-%m-%d").date()
        else:
            date = datetime.date.today()
        context['activePage'] = {'tree': 'ChannelPage', 'branch': 'index'}
        datas = get_datas_hourly(True, self.object.id, date)
        matches_data = get_datas_hourly(False,self.object.id, date)
        context['date'] = date
        context['labels'] = datas.keys()
        context['values'] = datas.values()
        context['matches_labels'] = matches_data.keys()
        context['matches_values'] = matches_data.values()
        return context

ExecutionLog的模型:

class ExecutionLog(models.Model):
    ACTION_TYPES = (
        (0, 'START'),
        (1, 'STOP'),
        (2, 'ASSIGNED'),
        (3, 'ERROR'),
        (4, 'OTHERS'),
    )
    type = models.IntegerField(default=0, choices=ACTION_TYPES)
    title = models.CharField(max_length=255)
    description = models.TextField(max_length=255, blank=True, null=True)
    date = models.DateTimeField(auto_now_add=True)
    execution = models.ForeignKey(Execution, related_name="execution_logs")

    class Meta:
        ordering = ['-date']

我想获取详细视图页面所属特定频道的ExecutionLog数据。

1 个答案:

答案 0 :(得分:1)

您可能需要覆盖get()方法,

def get(self, request, *args, **kwargs):
    self.object = self.get_object()
    context = self.get_context_data(object=self.object)
    return self.render_to_response(context)

您可以根据需要编辑视图。另外,请先了解DetailView的定义。

修改

def get_context_data(self, *args, **kwargs):
    context = super(ChannelDetailView, self).get_context_data(*args, **kwargs)

    if 'date' in self.request.GET:
        d = self.request.GET['date']
        date = datetime.datetime.strptime(d, "%Y-%m-%d").date()
    else:
        date = datetime.date.today()
    context['activePage'] = {'tree': 'ChannelPage', 'branch': 'index'}
    datas = get_datas_hourly(True, self.object.id, date)
    matches_data = get_datas_hourly(False,self.object.id, date)
    context['date'] = date
    context['labels'] = datas.keys()
    context['values'] = datas.values()
    context['matches_labels'] = matches_data.keys()
    context['matches_values'] = matches_data.values()
    context['executionLogs'] = ExecutionLog.objects.all()
    #^^^^^^^^^^^ You can access the execution logs in your template.
    return context

您必须遍历查询集并在模板中逐个访问属性,例如

{% for item in execution_log %} 
    {{ item.type }} 
    {{ item.title }}
    {{ item.description }}
    .....
{% endfor %}