Search code examples
pythondjangodatetimefilteringtastypie

How to filter an object based on a DateTimeField range in Python (Django) using Tastypie


How can one filter an object based on a datetime field range using Tastypie.

I have a Post model:

class Post(models.Model):
     title = models.CharField(max_length=40)
     postTime = models.DateTimeField(auto_now_add=True)
     description = models.CharField(max_length=140)

The post objects are retrieved through Tastypie. The range of objects I would like to retrieve are all the objects created from today to all the objects created 3 days ago. So I tried filtering the objects from the queryset as follows

RecentPosts(ModelResource):
     class Meta:
          queryset= Post.objects.filter(postTime__range=(date.today(), date.today() -timedelta(days=3)))
          resource_name = 'recent-posts'
          fields = ['id','postTime']
          authentication = BasicAuthentication()
          authorization =DjangoAuthorization()
          serializer = Serializer(formats=['json'])
          include_resource_uri = False
          filtering = {
                            'postTime': ALL,
                            'description': ALL,
          }

Even after doing this I'm unable to retrieve the objects. How else can I go about this?


Solution

  • After spending hours fiddling with different solutions, I finally found one that works. What I did was, instead of doing the filtering from the queryset I did the filtering in object_get_list Here is my solution. Also make sure you have the proper imports as well

     from datetime import datetime, timedelta
    
     RecentPosts(ModelResource):
     class Meta:
          queryset= Post.objects.all()
          resource_name = 'recent-posts'
          fields = ['id','postTime']
          authentication = BasicAuthentication()
          authorization =DjangoAuthorization()
          serializer = Serializer(formats=['json'])
          include_resource_uri = False
          filtering = {
                            'postTime': ALL,
                            'description': ALL,
          }
     get_object_list(self, request):
          return super(RecentPosts, self).get_object_list.filter(postTime__range=(datetime.now() - timedelta(days=3), datetime.now()))
    

    This will return all objects created from the current date to all the objects from 3 days ago. Try this solution out and let me know if it works for you.