我在UpdateView中获得了太多重复查询,每个Formset实例都有一个,我不知道如何在这种情况下使用prefetch_related。
我有一个模型,Entry,有多个Box实例(另一个模型)。每个盒子都有一个材料(第三个模型)。因此,当用户想要编辑条目时,如果它有10个框,Django将创建10个重复查询以获取每个框的每个材料。我之前使用了prefetch_related但没有使用多个Formset,因此我不知道该怎么做。这是相关的代码:
models.py
class Entry(models.Model):
# No Foreign keys here
class Box(models.Model):
....
material = models.ForeignKey('Material', on_delete=models.CASCADE)
class Material(models.Model:
# No Foreign keys here
views.py
class EntryUpdateView(UpdateView):
model = Entry
form_class = EntryForm
def get_context_data(self, **kwargs):
data = super(EntryUpdateView, self).get_context_data(**kwargs)
data['materials'] = Material.objects.all()
return data
def get(self, request, *args, **kwargs):
self.object = self.get_object()
form_class = self.get_form_class()
form = self.get_form(form_class)
box_form = BoxUpdateFormSet(instance=self.object)
return self.render_to_response(self.get_context_data(form=form, box_form=box_form))
models.py
class EntryForm(ModelForm):
class Meta:
model = Entry
fields = ...
class BoxForm(ModelForm):
class Meta:
model = Box
fields = ....
BoxUpdateFormSet = inlineformset_factory(Entry, Box, form=BoxForm, can_delete=True, extra=0)