Django rest framwork filter by year or month

How can i filter date by year or by month in django rest framework

my model

class DailyJues(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
amount = models.IntegerField()
date = models.DateField(default=timezone.now)

my views

class DailyJuesViews(APIView):
def get(self, request):
    daily_jues = DailyJues.objects.all()
    serializer = DailyJuesSerializers(daily_jues, 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)

Well you can filter with: DailyJues.objects.filter(date__year=2022) & DailyJues.objects.filter(date__month=2022)

I presume to use the API view you would just use GET/POST values..

Example Backend

class DailyJuesViews(APIView):
    def get(self, request):

        filterdict = {}
        if request.GET.get('year'):
            filterdict['date__year'] = request.GET.get('year')
        if request.GET.get('month'):
            filterdict['date__month'] = request.GET.get('month')

        # Note: If filterdict is empty it's the same as an .all()


        daily_jues = DailyJues.objects.filter(**filterdict)
        serializer = DailyJuesSerializers(daily_jues, many=True)
        return Response(serializer.data)

Post is very similar just use request.POST.get('month')

from django.db.models import Q

daily_jues = DailyJues.objects.filter(
    Q(date__year=2022) & Q(date__month=2022)
)
Back to Top