Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
172 views
in Technique[技术] by (71.8m points)

Django Rest Framework does not filter after resetting queryset

My url will be something like: ... /? Search = modal.

I want to replace the "modal" with empty "" to clean the filter and return all records.

Views.py

class AnexoExamesViewSet(viewsets.ModelViewSet):

search_fields = ['descr']
filter_backends = (filters.SearchFilter,)
queryset = AnexoExames.objects.all()
serializer_class = AnexoExamesSerializer

def get_queryset(self):
    queryset = AnexoExames.objects.all()
    search_descr = self.request.query_params.get('search',None)
    print(search_descr)
    if search_descr=='modal':            
        queryset = AnexoExames.objects.filter(descr='')                
    return queryset

This way it is returning zero results

question from:https://stackoverflow.com/questions/66055811/django-rest-framework-does-not-filter-after-resetting-queryset

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I've never found a django-filter that worked as I needed it to. I prefer this simple solution that you should be able to use to solve your problem:

views.py

# inherits APIView, ModelViewSet, etc.
class View(...):

    # override get_queryset method like so:
    def get_queryset(self):
        
        queryset = self.queryset
        custom_filter = self.request.query_params.get('filter')
        
        if custom_filter: 
            custom_filter = json.loads(custom_filter)
            queryset = queryset.filter(**custom_filter)
        
        return queryset

Then we can filter from javascript like so:

script.js

// create the django-like filter:
var filter = JSON.stringify({
  'modal__name' : 'My Modal Name',
})

var url = '.../api/test?filter=' + filter;

Your url will look like: .../api/test?filter={"modal__name":"My Modal Name"}


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...