如何使用Tastypie在Python(Django)中基于DateTimeField范围过滤对象

时间:2013-03-18 21:44:37

标签: python django datetime filtering tastypie

如何使用 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天前创建的所有对象。所以我尝试从查询集中过滤对象,如下所示

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,
          }

即使这样做,我也无法检索到这些物体。我怎么能这样做呢?

3 个答案:

答案 0 :(得分:6)

您是否尝试过使用

filtering = {
   "postTime": ['gte', 'lte'],
}

然后在调用资源的查询中添加

http://your.query/?postTime__lte=<SOME DATE>&postTime__gte=<SOME DATE>

您也可以选择

filtering = {
   "postTime": ['gte',],
}

filtering = {
   "postTime": ['lte',],
}

使用正确的查询。

答案 1 :(得分:5)

花了几个小时摆弄不同的解决方案后,我终于找到了一个有效的解决方案。我做的是,而不是从查询集中进行过滤,我在 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()))

这会将从当前日期创建的所有对象返回到3天前的所有对象。试试这个解决方案,让我知道它是否适合你。

答案 2 :(得分:1)

我有一个案例,我需要在查询本身处理它。基本上我想在查询中使用范围。我找不到任何答案。我是按照以下方式完成的。可以帮助别人:

filtering = {
  "postTime": ['range']
}

使用以下方式查询:

http://your.query/?postTime__range=<SOME DATE>,<SOME DATE>

返回这两天之间的所有记录!

相关问题