如何为Django Rest Framework指定过滤数据参数?

时间:2016-03-24 14:09:24

标签: python django django-rest-framework

我有这个型号:

class Entry(models.Model):
    time = models.DateTimeField()
    no2 = models.FloatField()
    co = models.FloatField()
    humidity = models.FloatField()
    temperature = models.FloatField()

和休息观点:

class DataList(ListAPIView):
    serializer_class = EntrySerializer

    def get_queryset(self):
        return Entry.objects.all()

我希望有下一个选项来通过get参数过滤数据(例如/ entries?period = week):

  1. 获取最后一个条目
  2. 获取过去7天的平均值
  3. 获取过去12个月的平均值。
  4. 如何通过django rest框架实现它?

2 个答案:

答案 0 :(得分:2)

您可以将参数带到get_queryset方法,并根据您的参数列出您的条目。

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

答案 1 :(得分:1)

确实,您可以通过调整get_queryset方法来实现此目的,但是通过api过滤的更好解决方案是使用django-filter包。 DRF支持这个开箱即用:)

# 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

然后在你的ApiView类中

class DataList(ListAPIView):
    queryset = Entry.objects.all()
    serializer_class = EntrySerializer
    # filtering part
    filter_backends = (DjangoFilterBackend,)
    filter_class = EntryFilter

使用它将使您的APIView类保持干净且更具可读性,并将过滤逻辑放置在应放置的位置..在过滤器中:)