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 に答える