Reputation: 1130
Creating a simple view to list three columns in between two date range. On doing some research I found that we have some Django ORM that we can use. Hence I have tried to impletemt it in my views as shown below.
from rest_framework.response import Response
import django_filters.rest_framework
from rest_framework.generics import ListAPIView
from .models import Revenue
from .serializers import DataListSerializers
# Create your views here.
class DataListView(ListAPIView):
serializer_class = DataListSerializers
pagination_class = None
queryset = Revenue.objects.all()
filter_backends = [django_filters.rest_framework.DjangoFilterBackend, django_filters.OrderingFilter]
def get_queryset(self):
time_filter = self.queryset.objects.filter(datefield__gte=<some_date>, datefield__lte=<some date>)
As you could see that I have written a simple ListAPIView
. When we execute the above query in the Django ORM console then we can give some date range. But how to incorporate the above query in the view? What would be the value for datefield__gte
, and datefield__lte
?
models.py
class Revenue(models.Model):
date = models.DateField(auto_now_add=True)
fname = models.CharField(max_length=100)
lname = models.CharField(max_length=100)
eno = models.CharField(max_length=100)
Upvotes: 1
Views: 2205
Reputation: 1130
I got the issue resolved with the help of ming's reply. Below is the final view.
class DataListView(ListAPIView):
serializer_class = DataListSerializers
pagination_class = None
queryset = Revenue.objects.all()
permission_classes = [permissions.AllowAny]
def get_queryset(self):
start_date = datetime.date.today()
end_date = start_date + datetime.timedelta(days=6)
time_filter = self.queryset.filter(date__range=(start_date, end_date))
ser = DataListSerializers(time_filter, many=True).data
return ser
With this I am able to store data for teh current date, but when I tried to upload a CSV file with older years data I am getting error. Well, I will open a different query for that. This post could be concluded as it solved the purpose
Upvotes: 4
Reputation: 876
you can use __range
to get some date range, like this:
time_filter = self.queryset.objects.filter(date__range=(<some_date>, <some_date>) )
Upvotes: 1