我有这个型号:
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):
如何通过django rest框架实现它?
答案 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类保持干净且更具可读性,并将过滤逻辑放置在应放置的位置..在过滤器中:)