Manytomany translatable fields in admin generate a lot of requests

I am using django-parler (derived from django-hvad) for translations. In admin, when displaying Foreignkey fields with manytomany relationships, django runs one query for each:

change_clinic__english____django_suit

change_clinic__english____django_suit

So when there are 300 services, there will be so many requests.

I think prefetch_related on get_queryset does not apply to filters / lists mantomany

, correct me if I am wrong:

def get_queryset(self, request):
    return super(DoctorAdmin, self).get_queryset(request).prefetch_related('translations', 'services__translations')

      

does not affect the number of requests. Enabling caching on the parrer (as the author suggested here ) also doesn't help, since the same queries are not repeated, but each element of these filters is called into the query for translated elements (the IDs are different each time). So what I am looking for is select_related / prefetch_related on internal filters. I'll also review your apps in the meantime if you've already solved this problem.

+3


source to share


2 answers


Hoping to be helpful to some others, here's how I solved the problem by reducing requests from 2k to 30 in admin:

class MyModelAdminForm(TranslatableModelForm):
    class Meta:
        model = MyModel
        exclude = ()

    def __init__(self, *args, **kwargs):
        super(MyModelAdminForm, self).__init__(*args, **kwargs)
        self.fields['services'].queryset = Service.objects.prefetch_related('translations').all()

class MyModelAdmin(TranslatableAdmin):

    form = MyModelAdminForm

      



So, override the form and once inside, override the prefetch query.

+4


source


It looks like you are using double underscore for a many-to-many table when it should be a single underscore. Also try adding to master table

try:



return super(DoctorAdmin, self).get_queryset(request).prefetch_related( 
    'services__service_translation__translations',
    'services__service_translation__master'
)

      

Displaying the models.py file will help.

+1


source







All Articles