如何使用Tastypie在Python(Django)中基于DateTimeField范围过滤对象 [英] How to filter an object based on a DateTimeField range in Python (Django) using Tastypie
问题描述
如何使用 Tastypie ,根据 datetime字段范围过滤对象。
How can one filter an object based on a datetime field range using Tastypie.
我有一个发布模式:
class Post(models.Model):
title = models.CharField(max_length=40)
postTime = models.DateTimeField(auto_now_add=True)
description = models.CharField(max_length=140)
通过 Tastypie 检索帖子对象。我想要检索的对象范围是从今天创建的所有对象,创建于3天前创建的所有对象。所以我试图从查询器中过滤对象,如下所示
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?
推荐答案
我所做的是,而不是从查询器中进行过滤,我在 object_get_list 中进行过滤,这是我的解决方案。还要确保你有正确的导入
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()))
这将从3天前将从当前日期创建的所有对象返回给所有对象。尝试这个解决方案,让我知道如果它适用于你。
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.
这篇关于如何使用Tastypie在Python(Django)中基于DateTimeField范围过滤对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!