2

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?

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

1 Comment

Just FYI, your initial if statement needs to be indented a level.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.