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

2 投票
3 回答
4688 浏览
提问于 2025-04-17 19:33

如何根据日期时间字段的范围来过滤一个对象,使用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获取的。我想获取的对象范围是从今天开始到三天前创建的所有对象。所以我尝试从查询集中过滤对象,方法如下:

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 个回答

1

我遇到过一个情况,需要在查询中处理这个问题。基本上,我想在查询里使用范围。我找不到任何答案。于是我用以下方式解决了这个问题。可能对某些人有帮助:

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

使用的查询:

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

这个查询会返回这两天之间的所有记录!

7

你有没有试过使用

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

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

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

你也可以选择

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

或者

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

用一个合适的查询。

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()))

这个方法会返回从今天开始到三天前创建的所有对象。试试这个方法,看看对你是否有效。

撰写回答