首页 > 解决方案 > Django 获取上下文数据

问题描述

是否可以“跳过”get_context_data 中的代码?

我有这个父类,每次我 context.update({}) 我想跳过或不运行父类中的某些键时都写了一个子类,因为它会影响性能,尤其是当父类中有多个查询时,而且我不希望他们在孩子身上,而是在父母身上的某些关键,val?

class Parent(ListView):
      ...
      context = super(Parent, self).get_context_data(**kwargs)
      queryset = Model.objects.all()
      context.update({
        "queries": querset,
        "grades": [1.75, 3.0]

      })
      return context

Class Child(Parent):
      context = super(Child, self).get_context_data(**kwargs)

      context.update({
        "migrate": True,

      })
      return context

在示例中,父类继承了具有 object_list 和 I context.update“查询”的 ListView。当在 Child 类中我想跳过/防止在 Child get_context_data 中运行 object_list 和查询时,我只希望在子类中继承一些类似“等级”,因为当父母查询集和 object_list 有数千个时,它会特别慢查询。

标签: pythondjangoinheritance

解决方案


您可以为此使用某种模板方法模式,但在 Parent 中使用默认行为而不是抽象方法。

class Parent(ListView):

    def get_context_data(self, **kwargs):
        context = super(Parent, self).get_context_data(**kwargs)
        queryset = self.get_custom_queryset()
        context.update({
            "queries": querset,
            "grades": [1.75, 3.0]

        })
        return context

    def get_custom_queryset(self):
        return Model.objects.all()


class Child(Parent):

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

        context.update({
            "migrate": True,
        })
        return context

    def get_custom_queryset(self):
        pass

推荐阅读