我从来没有优化过我的Django代码,我不确定我是否完全理解Django optimisation docs,所以你能告诉我这个FormView类是否可以以某种方式优化(我猜是的……)?
我担心的代码部分是患者查找:Patient.objects.get(patientId=self.kwargs['patientId'])
-它发生了3次……这是否意味着Django将命中数据库3次还是只命中一次?
这是否可以/是否应该优化,如果是-如何优化?
class PatientNotes(SingleObjectMixin, FormView):
slug_url_kwarg = 'patientId'
slug_field = 'patientId'
pk_url_kwarg = 'patientId'
template_name = "patient/patient_detail.html"
form_class = AddNewNoteForm
def get_queryset(self):
queryset = super(PatientNotes, self).get_queryset()
self.current_patient = Patient.objects.get(patientId=self.kwargs['patientId'])
my_result = queryset.filter(patient=self.current_patient)
return my_result
def post(self, request, *args, **kwargs):
self.object = Patient.objects.get(patientId=self.kwargs['patientId'])
return super().post(request, *args, **kwargs)
def form_valid(self, form):
self.object = form.save(commit=False)
self.object.patient = Patient.objects.get(patientId=self.kwargs['patientId'])
self.object.note_created_by_date = datetime.date.today()
self.object.save()
return super().form_valid(form)
def get_success_url(self):
return reverse('PatientDetailView', kwargs={'patientId': self.object.patient.patientId})
发布于 2018-06-04 03:52:20
这意味着您的视图包含将多次命中数据库的重复查询。
使用
class PatientNotes(SingleObjectMixin, FormView):
...
def get_queryset(self):
...
# This will hit the database to fetch patient object.
self.current_patient = Patient.objects.get(patientId=self.kwargs['patientId'])
...
def post(self, request, *args, **kwargs):
# This will also hit the database to fetch patient object.
self.object = Patient.objects.get(patientId=self.kwargs['patientId'])
...
def form_valid(self, form):
...
# This will also hit the database to fetch patient object.
self.object.patient = Patient.objects.get(patientId=self.kwargs['patientId'])
...
这被认为是在单个请求期间进行的重复查询。
要解决这个问题,可以考虑更新get
和post
方法,为get
请求将当前对象设置为None
。在FormView不需要更新现有对象的情况下,post
方法将在保存表单后设置当前对象。
我推荐使用UpdateView或CreateView,因为您试图设置self.object
,即当前对象,因为FormView用于处理表单,即仅验证和保存表单数据。
模型字段不应该是驼峰大小写的,Patient.patientId
应该是Patient.patient_id
,它们应该是小写的,用下划线分隔。
class PatientNotes(SingleObjectMixin, FormView):
model = Patient
slug_url_kwarg = 'patient_id'
slug_field = 'patient_id'
pk_url_kwarg = 'patient_id'
template_name = 'patient/patient_detail.html'
form_class = AddNewNoteForm
def get(self, request, *args, **kwargs):
self.patient_object = self.get_object()
return super().get(request, *args, **kwargs)
def post(self, request, *args, **kwargs):
self.patient_object = self.get_object()
return super().post(request, *args, **kwargs)
def form_valid(self, form):
self.object = form.save(commit=False)
self.object.patient = self.patient_object
self.object.note_created_by_date = datetime.date.today()
self.object.save()
return super().form_valid(form)
def get_success_url(self):
# view names should be lower cased separated by underscores.
return reverse('patient_detail_view', kwargs={'patient_id': self.patient_object.patient_id})
https://stackoverflow.com/questions/50665548
复制相似问题