簡體   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