Reputation: 5438
I have this model:
class Entry(models.Model):
time = models.DateTimeField()
no2 = models.FloatField()
co = models.FloatField()
humidity = models.FloatField()
temperature = models.FloatField()
and rest view:
class DataList(ListAPIView):
serializer_class = EntrySerializer
def get_queryset(self):
return Entry.objects.all()
I want to have next options to filter data via get parameters (like /entries?period=week):
How to implement it via django rest framework?
Upvotes: 2
Views: 1602
Reputation: 1268
Indeed You can do this by adjusting get_queryset
method, but better solution for filtering over api is to use django-filter
package. DRF support this out of the box :)
# filters.py
import django_filters
from rest_framework import filters
class EntryFilter(filters.FilterSet):
period = django_filters.MethodFilter()
class Meta:
model = Entry
fields = ('period', ) # here you can add any fields from Entry model
def filter_period(self, queryset, value):
if value == 'last':
pass
elif value == 'week':
pass
else:
pass # rest of your if's
return queryset
Then in your ApiView class
class DataList(ListAPIView):
queryset = Entry.objects.all()
serializer_class = EntrySerializer
# filtering part
filter_backends = (DjangoFilterBackend,)
filter_class = EntryFilter
Going with this will keep your APIView class clean and more readable and filtering logic is placed where it should be placed.. in filters :)
Upvotes: 1
Reputation: 3496
You can take parameter to your get_queryset method and list your entries according to your parameter.
class DataList(ListAPIView):
serializer_class = EntrySerializer
def get_queryset(self):
period = request.query_params.get('period')
if period == 'last': # for last entry
queryset = Entry.objects.last()
elif period == 'week':
# queryset for week
elif period == 'month':
# queryset for month
return queryset
Upvotes: 3