Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Translatable Manytomany fields in admin generate many queries

I am using django-parler (a derivative of django-hvad) for translations. In admin when displaying Foreignkey fields with manytomany relationship, django runs a single query for each:

change_clinic__english____django_suit

change_clinic__english____django_suit

So when there are 300 services there would be as many queries.

I think the prefetch_related on get_queryset doesn't apply to mantomany filters/lists, correct me if I am wrong:

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

has no effect on number of queries. Enabling caching on parler (as the author suggested here) also does not help since the same queries are not repeated but each item on those filters is called in a query for translated items (IDs are different each time). So, what I am looking for is a select_related/prefetch_related on inner filters. I will also review your apps meanwhile, in case you have solved such problem already.

like image 810
Danial Tz Avatar asked Mar 16 '23 09:03

Danial Tz


2 Answers

In the hope of being useful for some others, here is how I solved the problem, reducing the queries from 2k to 30 in the 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 queryset with prefetch.

like image 170
Danial Tz Avatar answered Mar 23 '23 09:03

Danial Tz


Looks like you are using a double underscore for the many-to-many table, when it should be a single underscore. Also try adding in the master table

try :

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

Showing the models.py file would help.

like image 41
wobbily_col Avatar answered Mar 23 '23 08:03

wobbily_col