问题
After having read through and completed the Django REST Framework tutorial, it is not completely obvious how one would implement a filter on a GET request. For example, ListAPIView is great for viewing all the instances of a Model in your database. However, if I wanted to limit the results (e.g. for a Book
model, I might want to limit the results by publication date or author, etc.). It seems the best way to do this would be to create a custom Serializer, View, etc. and basically write everything by hand.
Is there a better way?
回答1:
Search parameters are called filter parameters in terms of django-rest-framework. There are many ways to apply the filtering, check the documentation.
In most cases, you need to override just view, not serializer or any other module.
One obvious approach to do it, is to override view's queryset. Example:
# access to /api/foo/?category=animal
class FooListView(generics.ListAPIView):
model = Foo
serializer_class = FooSerializer
def get_queryset(self):
qs = super(FooListView, self).get_queryset()
category = self.request.query_params.get("category", None)
if category:
qs = qs.filter(category=category)
return qs
But, django-rest-framework allows to do such things automatically, using django-filter.
Install it first:
pip install django-filter
Then specify in your view, by what fields you want to filter:
class FooListView(generics.ListAPIView):
model = Foo
serializer_class = FooSerializer
filter_fields = ('category', )
This will do the same, as in previous example, but less code used.
There are many ways to customize this filtering, look here and here for details.
There is also a way to apply filtering globally:
REST_FRAMEWORK = {
'DEFAULT_FILTER_BACKENDS': ('rest_framework.filters.DjangoFilterBackend',)
}
来源:https://stackoverflow.com/questions/26924968/how-to-add-search-parameters-to-get-request-in-django-rest-framework