简体   繁体   English

Django get_context_data

[英]Django get_context_data

Is it possible to 'skip' a code in get_context_data?是否可以“跳过”get_context_data 中的代码?

I have this parent class and wrote a child class everytime I context.update({}) I want to skip or not run certain key in the parent class, cause it is affecting the performance, especially when parent class has multiple queries inside them, and I don't want them in the child but certain key, val in the parent?我有这个父类并且每次我都写了一个子类 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

here in the example Parent class inherits in ListView that has an object_list and I context.update "queries".在示例中,父类在 ListView 中继承,它有一个 object_list 和我 context.update “查询”。 When In Child class I want to skip/prevent from running in Child get_context_data the object_list and queries, I want only some of like 'grades' to be inherit in the child class, cause it is slowing specially when Parents queryset and object_list has thousands of queries.当在 Child 类中我想跳过/阻止在 Child get_context_data 中运行 object_list 和查询时,我只希望在子类中继承一些类似的“成绩”,因为当Parents queryset 和 object_list 有数千个时,它会特别变慢查询。

You could use some kind of template method pattern for that, but with a default behavior within Parent instead of an abstract method.您可以为此使用某种模板方法模式,但在 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