简单地将变量添加到Django上下文字典中

时间:2016-10-18 18:32:36

标签: python django dictionary

Django文档建议在基于类的视图中将变量添加到上下文字典中,如下所示:

def get_context_data(self, **kwargs):
        # Call the base implementation first to get a context
        context = super(PublisherDetail, self).get_context_data(**kwargs)
        # Add in a QuerySet of all the books
        context['book_list'] = Book.objects.all()
        return context

我的收集上下文函数中经常有很多变量,因此我的代码最终看起来像这样:

def get_context_data(self, **kwargs):
        context = super(PublisherDetail, self).get_context_data(**kwargs)
        a = 2
        b = 'hello'
        c = 75 # temp variable, not wanted in context dict
        d = a * c

        context['a'] = a
        context['b'] = b
        context['d'] = d
        return context

为避免将每个变量单独添加到上下文字典中,我已开始执行以下操作:

def get_context_data(self, **kwargs):
        context = super(PublisherDetail, self).get_context_data(**kwargs)
        a = 2
        b = 'hello'
        c = 75 # temp variable, not wanted in context dict
        d = a * c

        del c # delete any variables you don't want to add
        context.update({k:v for k,v in locals().copy().iteritems() if k[:2] != '__' and k != 'context'})
        return context

它似乎有效,但我对本地人()并不十分熟悉。我有什么理由不这样做吗?

1 个答案:

答案 0 :(得分:0)

使用locals是个糟糕的主意。只需直接添加上下文

def get_context_data(self, **kwargs):
    context = super(PublisherDetail, self).get_context_data(**kwargs)
    c = 75 # temp variable, not wanted in context dict

    context['a'] = 2
    context['b'] = 'hello'
    context['d'] = context['a'] * c
    return context