1👍
You have to override the get_queryset
method on your viewset and filter the prefetch_related
query:
def get_queryset(self):
# get the filter value
modelb_id = self.request.query_params.get('modelab__modelb__id', None)
queryset_modelab = ModelAB.objects.all()
# you can use django-filter class here too
if modelb_id:
queryset_modelab = queryset_modelab.filter(modelb_id=modelb_id)
queryset_modelab.select_related('modelb')
queryset = (ModelA.objects
.prefetch_related(
Prefetch('modelab_set', queryset=queryset_modelab))
.all())
# modela filter class will work on this queryset
return queryset
Source:stackexchange.com