问题
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?
回答1:
Have you tried to use
filtering = {
"postTime": ['gte', 'lte'],
}
and then in the query which is calling the resource add
http://your.query/?postTime__lte=<SOME DATE>&postTime__gte=<SOME DATE>
You can also choose
filtering = {
"postTime": ['gte',],
}
or
filtering = {
"postTime": ['lte',],
}
with a proper query.
回答2:
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.
回答3:
I had a case where I needed this to be handled in query itself. Basically I wanted to use range in the query. I couldn't find any answer. I have done it in the following way. Might help someone:
filtering = {
"postTime": ['range']
}
Query using:
http://your.query/?postTime__range=<SOME DATE>,<SOME DATE>
Returns all the records between these two days!
来源:https://stackoverflow.com/questions/15487537/how-to-filter-an-object-based-on-a-datetimefield-range-in-python-django-using