gpt4 book ai didi

python - 优化 django 查询以避免使用详细 View 和覆盖 get_context_data 时出现重复

转载 作者:行者123 更新时间:2023-12-01 08:12:35 24 4
gpt4 key购买 nike

我尝试在使用 CBV(例如 DetailView)时减少重复查询的数量,然后重写 get_context_data 以根据相关模型过滤模型。

现在,我有一个 PatientCase 模型的 DetailView,并希望在相关模型 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 行 patent_case = self.get_object() 因为 detail.py 调用 get_object 这就是创建第一个查询。有没有办法缓存它以在 get_context_data 中重用,或者可能是根本不需要 get_context_data 的更好方法?

最佳答案

DetailView中,get() method在调用 get_context_data 之前设置 self.object = get_object(),因此您不必再次调用 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

关于python - 优化 django 查询以避免使用详细 View 和覆盖 get_context_data 时出现重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55145823/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com