noa*_*ale 2 python django datetime filtering tastypie
如何使用Tastypie基于日期时间字段范围过滤对象.
我有一个Post模型:
class Post(models.Model):
title = models.CharField(max_length=40)
postTime = models.DateTimeField(auto_now_add=True)
description = models.CharField(max_length=140)
Run Code Online (Sandbox Code Playgroud)
邮件对象通过Tastypie检索.我想要检索的对象范围是从今天创建的所有对象到3天前创建的所有对象.所以我尝试从查询集中过滤对象,如下所示
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,
}
Run Code Online (Sandbox Code Playgroud)
即使这样做后我也无法检索对象.我还能怎么做呢?
你试过用吗?
filtering = {
"postTime": ['gte', 'lte'],
}
Run Code Online (Sandbox Code Playgroud)
然后在调用资源add的查询中
http://your.query/?postTime__lte=<SOME DATE>&postTime__gte=<SOME DATE>
Run Code Online (Sandbox Code Playgroud)
你也可以选择
filtering = {
"postTime": ['gte',],
}
Run Code Online (Sandbox Code Playgroud)
要么
filtering = {
"postTime": ['lte',],
}
Run Code Online (Sandbox Code Playgroud)
正确的查询.
花了几个小时摆弄不同的解决方案后,我终于找到了一个有效的解决方案.我做的是,而不是从查询集中进行过滤我在object_get_list中进行了过滤这是我的解决方案.还要确保您也有适当的进口
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()))
Run Code Online (Sandbox Code Playgroud)
这将从3天前将从当前日期创建的所有对象返回到所有对象.试试这个解决方案,让我知道它是否适合你.
| 归档时间: |
|
| 查看次数: |
4390 次 |
| 最近记录: |