Allow filtering transactions by stack and month

This commit is contained in:
Tanner Collin 2021-07-17 22:15:39 +00:00
parent aa4e8ae0e2
commit 7386cb52e0

View File

@ -2,6 +2,8 @@ from django.contrib.auth.models import User, Group
from rest_framework import viewsets, permissions from rest_framework import viewsets, permissions
from server.api import serializers, models from server.api import serializers, models
from datetime import datetime
class UserViewSet(viewsets.ModelViewSet): class UserViewSet(viewsets.ModelViewSet):
queryset = User.objects.all() queryset = User.objects.all()
@ -36,4 +38,20 @@ class TransactionViewSet(viewsets.ModelViewSet):
permission_classes = [permissions.IsAuthenticated] permission_classes = [permissions.IsAuthenticated]
def get_queryset(self): def get_queryset(self):
return self.queryset.filter(stack__account__users=self.request.user) queryset = self.queryset.filter(stack__account__users=self.request.user)
if self.action == 'list':
month = self.request.query_params.get('month', '')
stack = self.request.query_params.get('stack', '')
if month:
try:
dt = datetime.strptime(month, '%Y-%m')
except ValueError:
raise exceptions.ValidationError(dict(month='Should be YYYY-MM.'))
queryset = queryset.filter(created_at__year=dt.year)
queryset = queryset.filter(created_at__month=dt.month)
if stack:
queryset = queryset.filter(stack=stack)
return queryset.order_by('-created_at', '-id')