Django模型formset性能

时间:2016-01-15 15:46:41

标签: django performance django-forms modelform formset

我对Django 1.4.2和PostgreSQL 9.1几乎没有性能问题。我想创建模型fromset,其形式如下:

forms.py

class AcknowledgeForm(forms.ModelForm):

    class Meta:
        model = Attendance
        fields = ['acknowledge', ]
        widgets = {'acknowledge': forms.CheckboxInput()}


AcknowledgeFormset = forms.models.modelformset_factory(Attendance, form=AcknowledgeForm, extra=0)

用于少量ForeignKeys的模型

models.py

class Attendance(models.Model): #500k rows in DB
    zamestnani = models.ForeignKey('people.Zamestnani',  related_name='attendance') #~1k rows
    day = models.ForeignKey(Day) #~2.5k rows
    acknowledge = models.NullBooleanField(blank=True, null=True)

views.py

class VacationAcknowledgeView(LoginRequiredMixin, TemplateView):
    template_name = "presence/presence_vacation_acknowledge.html"
    http_method_names = ['get', 'post']

    def get_context_data(self, **kwargs):
        context = super(VacationAcknowledgeView, self).get_context_data()
        person = Person.fromRequest(self.request)
        first_day = date(date.today().year, 1, 1)
        days = Attendance.objects.filter(acknowledge=None,  day__date__gte=first_day, zamestnani__osoba=person)
        context['formset'] = AcknowledgeFormset(queryset=days)
        return context

    def post(self, request, *args, **kwargs):
        #next line is screwed
        formset = AcknowledgeFormset(request.POST)
        #never been there....
        return super(VacationAcknowledgeView, self).get(request, *args, **kwargs)

我可以创建它,渲染它,一切似乎都没问题,但是从POST中分配数据会导致服务器冻结,因为单个对象的时间非常短(小时)。

经过短暂挖掘我个人责备模型formset,因为当我创建它并处理它就像单一形式,一切都按预期工作。但我不知道如何修复/规避这一点。

感谢任何合理的建议。

1 个答案:

答案 0 :(得分:1)

您提到数据库中有{500}行用于Attendance模型。在Django中,当没有为queryset指定ModelFormSet参数时,它包括该模型中的所有对象。 Django可能正在获取所有500,000行数据。

您需要找出ModelFormSet的查询集。 E.g。

def post(self, request, *args, **kwargs):
    queryset = Attendance.objects.none()
    formset = AcknowledgeFormset(queryset=queryset, data=request.POST)
    # continue with your regular code execution

该文档包含ModelFormSethttps://docs.djangoproject.com/en/1.9/topics/forms/modelforms/#django.forms.models.BaseModelFormSet

的查询集的部分