我有一个模型窗体,可以在基于函数的视图中创建模型实例。 当create view呈现表单模板时,它将运行6个我想减少的查询。 有什么方法可以减少qs或增加模型创建视图的性能?
models.py
class Teacher(models.Model):
name = models.CharField(max_length=150)
photo = models.ImageField(upload_to='teachers',
default='teacheravatar.jpg')
date_of_birth = models.DateField(blank=True, null=True)
designation = models.ForeignKey(Designation, on_delete=models.CASCADE)
expertise = models.ManyToManyField(
to=Topic, blank=True, related_name='expert_in')
mobile = models.CharField(max_length=11, blank=True, null=True)
email = models.CharField(max_length=255, blank=True, null=True)
joining_date = models.DateField(auto_now=True)
class Meta:
ordering = ['joining_date', 'name']
*表格。py*
class TeacherForm(ModelForm):
class Meta:
model = Teacher
fields = ['name', 'photo', 'date_of_birth',
'designation', 'expertise',
'mobile', 'email', ]
* views.py *
# THIS VIEW DUPLICATES QUEREIS
# AND RUNS 6 QUERIES
@login_required
def add_teacher_view(request):
"""
:param request:
:return: teacher add form
"""
if request.method == 'POST':
form = TeacherForm(request.POST)
if form.is_valid():
form.save()
pk = form.instance.pk
return redirect('teachers:teacher_details', pk=pk)
form = TeacherForm()
context = {'form': form}
return render(request, 'teachers/add_teacher.html', context)