2

如何使用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,
          }

即使这样做了,我也无法检索对象。我还能怎么做呢?

4

3 回答 3

7

你试过用

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

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

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

你也可以选择

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

或者

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

通过适当的查询。

于 2013-03-18T22:32:41.423 回答
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 天前的所有对象。试试这个解决方案,让我知道它是否适合你。

于 2013-03-19T18:20:53.597 回答
1

我有一个案例,我需要在查询本身中处理这个问题。基本上我想在查询中使用范围。我找不到任何答案。我已经通过以下方式完成了。可能会帮助某人:

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

查询使用:

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

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

于 2017-02-28T09:24:36.523 回答