在使用详细信息视图和覆盖get_context_data时,优化django查询以避免重复

问题描述 投票:1回答:1

我正在尝试使用诸如DetailView之类的CBV来减少重复查询的数量,然后重写get_context_data以基于相关模型过滤模型。

现在,我有一个DetailView用于PatientCase模型,并希望在相关模型的上下文中创建两个变量CasePhotos关系是通过CasePhoto模型上的外键。

class CasePhoto(models.Model):
    ...
    patient_case = models.ForeignKey(PatientCase, on_delete=models.CASCADE)
    photo = models.URLField()
    is_mentor_edit = models.BooleanField(default=False)
    ...

现在,我知道这很糟糕,但我似乎无法找到正确的最佳方式来做到这一点。一些指导,甚至更好的一些我明显忽略的文档链接会更好。

class ReviewCaseView(DetailView):
    model = PatientCase

def get_context_data(self, **kwargs):
    patient_case = self.get_object()
    context = super().get_context_data(**kwargs)
    case_photos = CasePhoto.objects.filter(patient_case=patient_case)
    context['case_photos'] = case_photos.filter(is_mentor_edit=False)
    context['mentor_photos'] = case_photos.filter(is_mentor_edit=True)
    return context

我知道重复是第5行patient_case = self.get_object(),因为detail.py调用get_object,这是创建第一个查询。有没有办法缓存这个在get_context_data重用或者更好的方式没有get_context_data

python django python-3.x performance django-class-based-views
1个回答
1
投票

DetailViewget() method在打电话给self.object = get_object()之前设置了get_context_data,因此你不必再打电话给get_object()

def get_context_data(self, **kwargs):
    context = super().get_context_data(**kwargs)
    patient_case = self.object
    case_photos = CasePhoto.objects.filter(patient_case=patient_case)
    context['case_photos'] = case_photos.filter(is_mentor_edit=False)
    context['mentor_photos'] = case_photos.filter(is_mentor_edit=True)
    return context
© www.soinside.com 2019 - 2024. All rights reserved.