Django Inline for ManyToMany generate duplicate queries

后端 未结 3 785
南方客
南方客 2021-01-06 01:50

I\'m experiencing some major performing issue with my django admin. Lots of duplicate queries based on how many inlines that I have.

models.py

class          


        
3条回答
  •  独厮守ぢ
    2021-01-06 02:28

    Nowadays, (kudos to that question), BaseFormset receives a form_kwargs attribute.

    The ChoicesFormSet code in the accepted answer could be slightly modified as such:

    class ChoicesFormSet(forms.BaseInlineFormSet):
        def __init__(self, *args, **kwargs):
            super().__init__(*args, **kwargs)
            setting_choices = list(Setting.objects.values_list('id', 'name'))
            displayed_group_choices = list(DisplayedGroup.objects.values_list('id', 'name'))
            self.form_kwargs['setting_choices'] = self.setting_choices
            self.form_kwargs['displayed_group_choices'] = self.displayed_group_choices
    

    The rest of the code stays intact, as desscribed in the accepted answer:

    class ArrangementInlineForm(forms.ModelForm):
        class Meta:
            model = Arrangement
            exclude = ()
    
        def __init__(self, *args, **kwargs):
            setting_choices = kwargs.pop('setting_choices', [((), ())])
            displayed_group_choices = kwargs.pop('displayed_group_choices', [((), ())])
    
            super().__init__(*args, **kwargs)
    
            # This ensures that you can still save the form without setting all 50 (see extra value) inline values.
            # When you save, the field value is checked against the "initial" value
            # of a field and you only get a validation error if you've changed any of the initial values.
            self.fields['setting'].choices = [('-', '---')] + setting_choices
            self.fields['setting'].initial = self.fields['setting'].choices[0][0]
            self.fields['setting'].empty_values = (self.fields['setting'].choices[0][0],)
    
            self.fields['displayed_group'].choices = displayed_group_choices
            self.fields['displayed_group'].initial = self.fields['displayed_group'].choices[0][0]
    
    
    class ArrangementInline(admin.TabularInline):
        model = Arrangement
        extra = 50
        form = ArrangementInlineForm
        formset = ChoicesFormSet
    
        def get_queryset(self, request):
            return super().get_queryset(request).select_related('setting')
    
    
    class MachineAdmin(admin.ModelAdmin):
        inlines = (ArrangementInline,)
    
    
    admin.site.register(Machine, MachineAdmin)
    

提交回复
热议问题