How to resolve latency issue with django M2M and filter_horizontal in ModelAdmin panel?

I have used django ModelAdmin with M2M relationship and formfield filtering code as follows: But for superuser or any other login where the number of mailboxes are more than 1 lakh I have sliced the available after filtering. But loading the m2m field takes time and times out for superuser login:

  def formfield_for_manytomany(self, db_field, request, **kwargs):
        if db_field.name == "mailboxes":
            if request.user.is_superuser:
                    queryset = Mailbox.objects.all().only('id','email')
                    kwargs["queryset"] = queryset
                    field = super().formfield_for_manytomany(db_field, request, **kwargs)
                    field.widget.choices.queryset = queryset[:300]  # Limit visible options
                    return field
    
    
            if request.user.groups.filter(name__in=['customers']).exists():
                queryset = Mailbox.objects.only('id', 'email').filter(
                    domain__customer__email=request.user.email
                )
                kwargs["queryset"] = queryset
                field = super().formfield_for_manytomany(db_field, request, **kwargs)
                field.widget.choices.queryset = queryset[:500]  # Limit visible options
                return field
        return super().formfield_for_manytomany(db_field, request, **kwargs)

I want to use filter_horizontal only and not django auto_complete_light or any javascript.how can the latency be resolved. As you can see the queryset filtering is already done to get valid options and then sliced.

Вернуться на верх