Vassily
Vassily

Reputation: 5438

How to specify filtering data parameters for Django Rest Framework?

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):

  1. Get last entry
  2. Get average values for each of last 7 days
  3. Get average values for each of last 12 months.

How to implement it via django rest framework?

Upvotes: 2

Views: 1602

Answers (2)

qwetty
qwetty

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

Cagatay Barin
Cagatay Barin

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

Related Questions