繁体   English   中英

Django get_context_data

[英]Django get_context_data

是否可以“跳过”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

在示例中,父类在 ListView 中继承,它有一个 object_list 和我 context.update “查询”。 当在 Child 类中我想跳过/阻止在 Child get_context_data 中运行 object_list 和查询时,我只希望在子类中继承一些类似的“成绩”,因为当Parents queryset 和 object_list 有数千个时,它会特别变慢查询。

您可以为此使用某种模板方法模式,但在 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM