python - 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 有数千个时,它会特别慢查询。
解决方案
您可以为此使用某种模板方法模式,但在 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
推荐阅读
- unit-testing - .toHaveBeenCalledWith Jasmine.objectContaining 部分匹配而不命名所有键
- google-api - 发现日历房间(资源)是否可以通过 Google Calendar API 预订
- cordova - cordova buildConfig 没有配置 Xcode 项目?
- c++ - 扩展 MAPI - 阅读邮件正文在每个字符后添加空格字符
- php - XAMPP 上的 TYPO3:后端的更改未/不可靠地持续
- sql - SQL Server 中的计数总和
- asp.net-mvc-4 - Razor cshtml table multiple thead tr's
- flutter - 如何停止键盘弹出问题是 TextField 颤动
- facebook-graph-api - Facebook Graph API : empty results when trying to reach leads on LeadgenForms
- c# - Azure Storage CloudBlobContainer.Exists permissions