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

标签 python django django-rest-framework

我有这个模型:

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

和休息 View :

class DataList(ListAPIView):
    serializer_class = EntrySerializer

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

我想要通过获取参数(如/entries?period=week)过滤数据的下一个选项:

  1. 获取最后一个条目
  2. 获取过去 7 天每天的平均值
  3. 获取过去 12 个月每个月的平均值。

如何通过django Rest框架实现它?

最佳答案

您可以将参数传递给 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

关于python - 如何为Django Rest Framework指定过滤数据参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36202194/

相关文章:

python - RobotFramework - 如何从关键字返回值并停止?

python - Pygame:将名称限制为 3 或 4 个字母

django - 从 django-allauth 中删除 'username' 字段

django - Django ViewSet中detail参数的含义是什么?

python - Django Rest Framework关系属性错误

python - 有没有办法允许 Django 休息框架的空白数据

python - PIP 安装包不正确或安装在错误的位置

python - 使用 Pygame 检测碰撞点

python - 由于 errno : 150 "Foreign key constraint is incorrectly formed",Django 1.8 应用程序初始迁移神秘失败

python - 在 Django 中运行并与后台进程通信