You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Django REST Framework中按年份或月份筛选日期

在Django REST Framework中按年份/月份筛选日期

你可以通过解析请求的查询参数,结合Django ORM的__year和__month字段查询来实现日期筛选。以下是修改后的视图代码:

修改后的视图实现

from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from .models import DailyJues
from .serializers import DailyJuesSerializers

class DailyJuesViews(APIView):
    def get(self, request):
        queryset = DailyJues.objects.all()
        
        # 从查询参数中获取年份和月份
        year = request.query_params.get('year')
        month = request.query_params.get('month')
        
        # 处理筛选条件,转换为整数避免类型错误
        try:
            if year:
                queryset = queryset.filter(date__year=int(year))
            if month:
                queryset = queryset.filter(date__month=int(month))
        except ValueError:
            return Response({"error": "年份或月份必须是整数格式"}, status=status.HTTP_400_BAD_REQUEST)
        
        serializer = DailyJuesSerializers(queryset, many=True)
        return Response(serializer.data)

    def post(self, request):
        serializer = DailyJuesSerializers(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

调用方式

你可以通过在请求URL后添加查询参数来触发筛选:

  • 按年份筛选:GET /your-api-endpoint/?year=2024
  • 按月份筛选:GET /your-api-endpoint/?month=5
  • 同时按年月筛选:GET /your-api-endpoint/?year=2024&month=5

补充说明

  • date__year和date__month是Django ORM针对DateField提供的内置查询条件,会自动提取日期中的对应部分进行匹配。
  • 加入try-except块是为了处理参数非整数的情况,返回明确的错误提示。

内容的提问来源于stack exchange,提问作者kevin Pineda

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 06:25:27